我有3个名为Article
,User
,Comment
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
,我该怎么办?
答案 0 :(得分:3)
没有直接的方法
但我遵循这种方式
@comment = @article.comments.build(comment_params.merge(user: current_user))