开发者

Associated model is not saving data when page is refreshed

开发者 https://www.devze.com 2023-03-22 14:57 出处:网络
Rails 3.1 RC4 I have a 1:1 association between User and Profile. When I submit the new profile form, the data I\'ve entered is displayed just fine (see screenshot: http://i.imgur.com/fY8YU.png), but

Rails 3.1 RC4

I have a 1:1 association between User and Profile. When I submit the new profile form, the data I've entered is displayed just fine (see screenshot: http://i.imgur.com/fY8YU.png), but when I refresh it the data is instantly wiped.

Could anyone tell me what is causing this?

Here's the submit form:

<%= form_for([@user, @user.build_profile]) do |f| %>

<div class="field">

<%= f.label :first_name %><br />

<%= f.text_field :first_name %>

</div>

<div class="field">

<%= f.label :last_name %><br />

<%= f.text_field :last_name %>

</div>

<div class="field">

<%= f.label :picture %><br />

<%= f.text_field :picture %>

</div>

<div class="field">

<%= f.radio_button(:sex, "male") %>

<%= f.label(:sex, "Male") %>

<%= f.radio_button(:sex, "female") %>

<%= f.label(:sex, "Female") %>

</div>

<div class="actions">

<%= f.submit %>

</div>

<% end %>

Here's the users_controll开发者_如何学运维er: https://github.com/imjp/SuperModel/blob/master/app/controllers/users_controller.rb

Here's the profiles_controller: https://github.com/imjp/SuperModel/blob/master/app/controllers/profiles_controller.rb


I'm not sure I agree with your approach. Why don't you do something like this:

In models/user.rb:

accepts_nested_attributes_for :profile

In controllers/users_controller.rb:

def new
  @user = User.new
  @user.build_profile
end

In views/users/_form.html.erb:

<%= form_for @user do |f| %>
  <%= f.text_field :first_name %>
  <%= f.fields_for :profile do |pf| %>
    <%= pf.text_field :some_profile_field %>
  <% end -%>
<%- end -%>

This isn't copied or tested, but it should work. On saving your user, the profile fields are sent along and validated with the user fields and are re-rendered when rendering the form again after a save error. This way you will keep full control over your form and its contents with minimal effort.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号