【问题标题】:How to db:seed a model and all its nested models?如何分贝:种子模型及其所有嵌套模型?
【发布时间】:2011-05-24 02:38:55
【问题描述】:

我有这些课程:

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])

【问题讨论】:

    标签: ruby-on-rails-3 seed


    【解决方案1】:

    您的用户模型需要设置为通过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:查看问题以获得更好的解决方案。

    【讨论】:

    • 是的,一切都设置好了(我已经有了视图,它们都工作正常)。但是为什么它在 db:seed 中失败是问题
    • 您在此处发帖时是否从您的模型中删除了accepts_nested_attributes
    • 是的,我只发布了模型的要点。我将添加所有细节。道歉:)
    • 您是否尝试过分别创建联系人和 user_profile,然后将它们分配给用户?如果需要,我可以发布一个示例。
    • 是的,它们分开工作,但我正在寻找更优雅的东西.. :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多