[英]how to build a record with multiple references with has many association in rails
我有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
但是,如果我想像article_id
這樣自動填充user_id
,該怎么辦?
沒有直接的方法可以做到這一點
但是我遵循這種方式
@comment = @article.comments.build(comment_params.merge(user: current_user))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.