如何使用多个引用构建记录,在rails中有很多关联

时间:2017-05-17 12:02:38

标签: ruby-on-rails ruby-on-rails-3

我有3个名为ArticleUserComment

的模型
class Article < ActiveRecord::Base
  has_many :comments
end

class User < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :article
end

现在,如果我想为文章建立评论,我可以使用

@comment = @article.comments.build(comment_params)

这会将article_id添加到comment对象。

现在,如果我想将user_id添加到object,我可以按以下方式添加

@comment.user_id = current_user.id

但是,如果我想像user_id那样自动填充article_id,我该怎么办?

1 个答案:

答案 0 :(得分:3)

没有直接的方法

但我遵循这种方式

@comment = @article.comments.build(comment_params.merge(user: current_user))