如何在 rails 中建立具有多个关联的记录

how to build a record with multiple references with has many association in rails

我有 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

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

没有直接的方法

但我是这样走的

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