簡體   English   中英

如何建立具有多個引用且在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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM