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

2023-12-08

我有这些课程:

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 or contacts表。也不会出现错误。

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

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

您的用户模型需要设置为接受嵌套属性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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何 db:seed 模型及其所有嵌套模型? 的相关文章