我正在编写 Rails 教程,但我不知道是什么
@comment.article_id = params[:article_id]
在代码中做:
def create
@comment = Comment.new(comment_params)
@comment.article_id = params[:arcticle_id]
@comment.save
redirect_to article_path(@comment.article)
end
另外,是否params[:article_id]
转移到左侧的实例变量中?
你需要阅读 Rails “Active Record Associations”
class Article < ApplicationRecord
has_many :comments, dependent: :destroy
end
class Comments < ApplicationRecord
belongs_to :article
end
当您创建has_many
和belongs_to
表关系之间的两个你需要存储article.id
在注释表,则注释与该特定文章。
在您的代码中:
def create
@comment = Comment.new(comment_params)
@comment.article_id = params[:arcticle_id]
@comment.save
redirect_to article_path(@comment.article)
end
您正在为一篇文章创建评论,因此当您这样做时
@comment.article_id = params[:arcticle_id]
它将在此评论中存储 article.id,因此此评论与该特定文章相关。
读取活动记录关联
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句