[英]how to build a record with multiple references with has many association in rails
I have 3 models named Article
, User
, Comment
我有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
Now, if I want to build a comment for an article, I can use 现在,如果我想对文章发表评论,可以使用
@comment = @article.comments.build(comment_params)
This will add article_id
to the comment
object. 这会将article_id
添加到comment
对象。
Now, if I want to add the user_id
to object
, I can add in the following way 现在,如果我想将user_id
添加到object
,可以按以下方式添加
@comment.user_id = current_user.id
But, if I want to auto populate user_id
like article_id
, how can I do? 但是,如果我想像article_id
这样自动填充user_id
,该怎么办?
There's no direct way of doing that 没有直接的方法可以做到这一点
But I follow this way 但是我遵循这种方式
@comment = @article.comments.build(comment_params.merge(user: current_user))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.