如何db:播种模型及其所有嵌套模型?

时间:2010-12-11 23:50:23

标签: ruby-on-rails-3 seed

我有这些课程:

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 => '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'
    }
  }
}])

记录会插入到users表中,但不会插入到user_profilescontacts表中。也没有错误发生。

做这样事的正确方法是什么?

解决 (感谢@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])

1 个答案:

答案 0 :(得分:3)

您的用户模型需要设置为通过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)

<击>

编辑3:查看问题以获得更好的解决方案。