
[英]Comment form not working? (Ruby on Rails) undefined method `comments' for nil:NilClass
[英]undefined method `comment' for nil:NilClass (ruby on rails)
在 Ruby on Rails 中,我试图呈现一个 JSON 文件,它将每个评论映射到评论。 每个评论都有很多评论,但每个评论都属于一个评论。
这是我生成 JSON 文件的控制器:
reviews: @ship.reviews.preload(:user_profile).map do |review|
{
id: review.id,
body: review.body,
rating: review.rating,
user_profile: review.user_profile,
comments: @review.comments.preload(:comment).map do |comment|
{
id: comment.id,
body: comment.body,
user_profile: comment.user_profile_id,
}
end
}
这是评论模型:
class Comment < ApplicationRecord
belongs_to :user_profile
belongs_to :review
end
这是 review.rb 模型:
class Review < ApplicationRecord
belongs_to :user_profile
belongs_to :ship
has_many :comments
has_many :helpfuls
end
但是我的 JSON 文件返回错误:
undefined method `comment' for nil:NilClass
在这一行:
comments: @review.comment.preload(:comment).map do |comment|
从 @review.comments.preload(:comment).map 中删除.preload(:commment)
@review.comments.preload(:comment).map do |comment|
. 你根本不需要它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.