Ruby on Rails:创建父级时使用默认值构建子级
我有父母和孩子的模型关系。在子模型的migration.rb 中,子模型的每个列都有默认值(parent_id 列除外)。
当我创建一个新的父对象时,如何才能创建一个子对象并将其保存到其表中,其中包含默认值的数据以及parent_id?
我认为这与父模型上的 after_create
之类的东西有关,但我不确定如何设置它。
I have a parent and child model relationship. In the child's migration.rb, the child model's columns each have default values (except the parent_id column).
When I make a new parent object, how can I make it so that a child object is created and saved into its table with the data from the default values along with the parent_id?
I'm thinking that it will have to do with something like an after_create
on the parent model, but I'm not sure how to set it up.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
修订:我修订了答案以使用 before_create 并构建(而不是创建)关联模型。一旦保存了父模型,ActiveRecord 机制就会负责保存关联的模型。
我什至测试了这段代码!
添加...
构建方法由拥有模型的机器通过 has_many 语句添加。由于该示例使用 has_many :doors (模型名称 Door),因此构建调用为 Doors.build
请参阅 has_many 和 has_one 的文档> 查看添加的所有其他方法。
Rails 2.x 引入了关联的自动保存选项。我认为它不适用于上述内容(我使用的是默认值)。 自动保存测试结果。
Revised: I revised the answer to use before_create and building, not creating, the associated models. The ActiveRecord machinery then takes care of saving the associated models once the parent is saved.
I even tested this code!
Added...
The build method is added by the owning model's machinery by the has_many statement. Since the example uses has_many :doors (model name Door), the build call is doors.build
See the docs for has_many and has_one to see all of the additional methods that are added.
Rails 2.x introduced the autosave option for associations. I don't think it applies to the above (I'm using default). Autosave testing results.
您没有指定(或者我读过了)您正在使用哪种关系。如果您使用一对一关系,例如“has_one”,则创建将不起作用。在这种情况下,你必须使用类似这样的东西:
在parent.rb
after_create 也可能有效,尚未测试。
在 child.rb 中,
当我在当前的应用程序中设置用户模型时,我在这个问题上遇到了很大的困难。
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods。 html
您可以看到 has_one 不支持parent.build 或parent.create
希望这会有所帮助。我本人对 Ruby 很陌生,并且慢慢地开始穿越 Ruby 丛林。一次愉快的旅程,但很容易迷路。:)
You didnt specify (or I overread it) what kind of relationship you are using. If you are using a one-to-one relationship, such as "has_one" create wont work. In this case you have to use something like this:
in parent.rb
after_create might work as well, havent tested that.
while in child.rb
I was struggling with this quite a bit when setting up a user model in my current application.
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
You can see that has_one does not support parent.build or parent.create
Hope this helps. Im new to Ruby myself and slowly starting to make my way through the Ruby jungle. A nice journey but easy to get lost in. :)