Nested Form Update in Rails 3 sets foreign key as NULL
I am trying to update a user record using a formtastic nested form. Its structure is as ollows
User
Admin
Address
When I send the form to update details, while updating the address or admin record, the user_id(foreign key) gets set to NULL. This is the data that gets sent and it seems to be ok.
Parameters: {
"utf8"=>"✓", "authenticity_token"=>"some token",
"user"=>{
"id"=>"16",
"first_name"=>"User",
"last_name"=>"Name",
"email"=>"username@gmail.com",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]",
"address_attributes"=>{
"main_phone"=>"131231233",
"address1"=>"Address 1 Line",
"address2"=>"Address 2 Line",
"city"=>"Lansing",
"state"=>"Michigan",
"zip"=>"48823",
"user_id"=>"16"
},
"admin_attributes"=>{
"company_id"=>"2",
"user_id"=>"16"
},
"roles_mask"=>"1",
"user_id"=>"16"
},
"commit"=>"Update User Roles",
"company_id"=>"2",
"id"=>"16"
}
User Model
class User < ActiveRecord::Base
has_one :address, :dependent => :destroy, :inverse_of => :user
has_one :admin, :dependent => :destroy, :inverse_of => :user
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :roles_mask, :terms_of_use,:id
attr_accessible :owner_attributes, :admin_attributes, :address_attributes, :client_attributes
accepts_nested_attributes_for :owner, :admin, :client, :address
end
Admin Model
class Admin < ActiveRecord开发者_如何学Go::Base
belongs_to :company
belongs_to :user, :inverse_of => :admin
attr_accessible :company_id, :user_id
end
*Address Model
class Address < ActiveRecord::Base
belongs_to :user, :inverse_of => :address
attr_accessible :address1, :user_id, :address2, :city, :state, :zip, :main_phone, :cell_phone
end
Could you please help me with this. Thanks.
UPDATED with the model details. I removed the validation to keep it short.
Try to correct
accepts_nested_attributes_for :owner, :admin, :client, :address
in your User model with
accepts_nested_attributes_for :owner, :client
accepts_nested_attributes_for :admin, :address, :update_only => true
精彩评论