Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 3 如何为一个模型及其所有嵌套模型种子?_Ruby On Rails 3_Seed - Fatal编程技术网

Ruby on rails 3 如何为一个模型及其所有嵌套模型种子?

Ruby on rails 3 如何为一个模型及其所有嵌套模型种子?,ruby-on-rails-3,seed,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

我有以下课程:

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'
    }
  }
}])
记录会插入到
用户
表中,但不会插入到
用户配置文件
联系人
表中。也没有发生错误

做这种事的正确方法是什么

已解决 (感谢@Austin L.的链接)


您的用户模型需要通过
accepts\u nested\u attributes

有关更多信息和示例,请参阅Rails文档:

编辑:也可以考虑使用<代码> HasyOne:CONTION:ION=>:USER配置文件< /C> >,这样您就可以访问这样的联系人:<代码>联系=用户。首先,联系< /代码> ./P> 编辑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\u nested\u属性
?是的,我只发布了模型的要点。我将添加所有细节。抱歉:)您是否尝试分别创建联系人和用户档案,然后将其分配给用户?如果需要的话,我可以发布一个例子。是的,它们是分开工作的,但我在寻找更优雅的东西:)
@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)