Zab*_*bba 5 seed ruby-on-rails-3
我有这些课程:
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
Run Code Online (Sandbox Code Playgroud)
我正在尝试将记录插入到所有3个表中,如下所示:
consumer = User.create!(
[{
:email => 'consu@a.com',
: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'
}
}
}])
Run Code Online (Sandbox Code Playgroud)
一个记录被插入到users
表中,但不进user_profiles
或contacts
表.也没有错误发生.
做这样的事情的正确方法是什么?
已解决 (感谢@Austin L.的链接)
params = { :user =>
{
:email => 'consu@a.com',
: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])
Run Code Online (Sandbox Code Playgroud)
您的用户模型需要设置为接受嵌套属性accepts_nested_attributes
有关更多信息和示例,请参阅 Rails 文档:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
编辑:此外,您可能需要考虑使用has_one :contact, :through => :user_profile
允许您访问联系人的方式,如下所示:@contact = User.first.contact
。
编辑2:在尝试了rails c
最佳解决方案后,我能找到的是:
@c = Contact.new(#all of the information)
@up = UserProfile.new(#all of the information, :contact => @c)
User.create(#all of the info, :user_profile => @up)
Run Code Online (Sandbox Code Playgroud)
编辑3:查看问题以获得更好的解决方案。
归档时间: |
|
查看次数: |
4110 次 |
最近记录: |