如何只是社员记录创建后正确地创建一个相关的记录? [英] How to properly create a associated record just after the associator record creation?

查看:155
本文介绍了如何只是社员记录创建后正确地创建一个相关的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的Rails 4.1 Ruby和我想知道的如果是好的的和的什么是只是该相关记录创建后创建相关的记录的弊端。也就是说,例如,我有文章类和注释 belongs_to的 文章,我想创建创建文章后,只是一个默认的评论。

I am using Ruby on Rails 4.1 and I would like to know if it is good and what are the drawbacks of creating a associated record just after the associator record creation. That is, for example, I have the Article class and the Comment class that belongs_to Article and I would like to create a "default" comment just after an article is created.

也许我可以用一个回调方法来实现这个目标,但是否有其他方法来完成我想要?我应该在什么是平衡(如:类/模块依赖关系)?

Probably I can use a callback method to accomplish that, but are there other approaches to accomplish what I looking for? What should I look at to be "balanced" (eg: class/module dependencies)?

推荐答案

您正在寻找沿...东西线

You are looking for something along the lines of...

Class Article

  has_many :comments

  after_create :create_first_comment!

  def create_first_comment!
    comments.create
  end

end

这篇关于如何只是社员记录创建后正确地创建一个相关的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆