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

编程入门 行业动态 更新时间:2024-10-25 16:17:10
本文介绍了如何 db: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 个表中,如下所示:

I'm trying to insert a record into all 3 tables like this:

consumer = User.create!( [{ :email => 'consu@a', :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 或 contacts 表中.也没有出现错误.

A record gets inserted into users table, but not into the user_profiles or contacts tables. No error occurs either.

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

What's the right way to do such a thing?

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

SOLVED (thanks @Austin L. for the link)

params = { :user => { :email => 'consu@a', :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

Your user model needs to be setup to accept nested attributes via accepts_nested_attributes

有关更多信息和示例,请参阅 Rails 文档:api.rubyonrails/classes/ActiveRecord/NestedAttributes/ClassMethods.html

See the Rails documentation for more info and examples: api.rubyonrails/classes/ActiveRecord/NestedAttributes/ClassMethods.html

你也可以考虑使用 has_one :contact, :through =>:user_profile 这将允许您像这样访问联系人:@contact = User.first.contact.

Also you might want to consider using has_one :contact, :through => :user_profile which would allow you to access the contact like this: @contact = User.first.contact.

Edit 2: 在 rails c 中玩完之后,我能找到的最佳解决方案是:

Edit 2: After playing around in rails c the best solution I can find is this:

@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:查看问题以获得更好的解决方案.

Edit 3: See the question for a better solution.

更多推荐

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

本文发布于:2023-11-24 05:25:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624109.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   嵌套   db   seed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!