Wednesday, 21 August 2013

how to make values appear in forms when form has model with associations with other models in rails

how to make values appear in forms when form has model with associations
with other models in rails

This form makes sure that the data already in the database is displayed in
it if the user has previously entered them and has now come back to update
the already given data or new data.
<%= simple_form_for resource, :as => resource_name, :url =>
registration_path(resource_name), :html => { :method => :put, :multipart
=> true } do |f| %>
<%= devise_error_messages! %>
<div id="tabs-1" class="ui-tabs-panel">
<div><%= f.label :email %><br />
<%= f.email_field :email, :autofocus => true, :readonly => true %></div>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
<div>Currently waiting confirmation for: <%= resource.unconfirmed_email
%></div>
<% end %>
<div><%= f.label :password %> <i>(leave blank if you don't want to
change it)</i><br />
<%= f.password_field :password, :autocomplete => "off" %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></div>
<div><%= f.label :current_password %> <i>(we need your current
password to confirm your changes)</i><br />
<%= f.password_field :current_password %></div>
</div>
Now this works as required. Now consider the situation where this model User
has_one :profile associations
with the profile model and also has
accepts_nested_attributes_for :profile
in the user.rb file.
Now coming back to the form if inside the above form we have the following
<%= f.fields_for :profile, @user.profile do |prof| %>
<% if @user.profile.first_name ==nil %>
<%= prof.label :first_name%><br/>
<%= prof.text_field :first_name %>
<%else%>
<div class="field">
<%= prof.label :first_name %><br />
<%= prof.text_field :first_name %>
</div>
<%end%>
<div class="field">
<%= prof.label :last_name %><br />
<%= prof.text_field :last_name %>
</div>
<div class="field">
<%= prof.label :address %><br />
<%= prof.text_area :address %>
</div>
Now no data that has been already entered by the user is seen in the form
when he comes back to update the form. Why is this happening?

No comments:

Post a Comment