5
我有這些類:如何分貝:種子模型及其所有嵌套模型?
class User
has_one :user_profile
accepts_nested_attributes_for :user_profile
attr_accessible :email, :password, :password_confirmation, :user_profile_attributes
end
class UserProfile
has_one :contact, :as => :contactable
belongs_to :user
accepts_nested_attributes_for :contact
attr_accessible :first_name,:last_name, :contact_attributes
end
class Contact
belongs_to :contactable, :polymorphic => true
attr_accessible :street, :city, :province, :postal_code, :country, :phone
end
我想記錄插入所有3個表是這樣的:
consumer = User.create!(
[{
:email => '[email protected]',
:password => 'aaaaaa',
:password_confirmation => 'aaaaaa',
:user_profile => {
:first_name => 'Gina',
:last_name => 'Davis',
:contact => {
:street => '221 Baker St',
:city => 'London',
:province => 'HK',
:postal_code => '76252',
:country => 'UK',
:phone => '2346752245'
}
}
}])
的記錄被插入到users
表,但不進user_profiles
或contacts
表。沒有錯誤發生。
什麼是做這種事情的正確方法?
解決 (感謝@Austin L.的鏈接)
params = { :user =>
{
:email => '[email protected]',
:password => 'aaaaaa',
:password_confirmation => 'aaaaaa',
:user_profile_attributes => {
:first_name => 'Gina',
:last_name => 'Davis',
:contact_attributes => {
:street => '221 Baker St',
:city => 'London',
:province => 'HK',
:postal_code => '76252',
:country => 'UK',
:phone => '2346752245'
}
}
}
}
User.create!(params[:user])
是的,它是所有設置(我已經有了意見,他們都工作正常)。但爲什麼它在db中失敗:種子是問題 – Zabba 2010-12-11 23:56:29
當你在這裏發佈時,是否從模型中刪除了'accep_nested_attributes'? – 2010-12-11 23:57:35
是的,我只發佈了模型的要點。我會添加所有的細節。道歉:) – Zabba 2010-12-12 00:00:46