Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Devise with has_one, Nested attributes not updated

I am creating a one-to-one relationship to user called user_info. Below is the working solution.

In user.rb

has_one :user_info
accepts_nested_attributes_for :user_info, :allow_destroy => true
attr_accessible :username, :email, :password, :password_confirmation, :remember_me, :user_info_attributes

In user_info.rb

belongs_to :user
attr_accessible :first_name, :last_name

In devise/registrations/edit.html.erb

<% resource.build_user_info if resource.user_info.nil? %>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %>
    ...
    <%= f.fields_for :user_info do |info| %>
        <%= info.text_field :first_name %>

I understand that I should not include the build in the view. But I do not want to 'touch' the devise controller or model. This is the easiest way.

like image 567
Min Ming Lo Avatar asked Oct 10 '22 18:10

Min Ming Lo


2 Answers

Turns out that the build line is not working properly in the view.

Should be: <% resource.build_user_info if resource.user_info.nil? %>

like image 144
Min Ming Lo Avatar answered Oct 13 '22 10:10

Min Ming Lo


Try :autosave => true on your call to accepts_nested_attributes_for

like image 26
janders223 Avatar answered Oct 13 '22 12:10

janders223