Ruby on rails 未定义的方法`注释';对于nil:NilClass(RubyonRails)
在RubyonRails中,我试图呈现一个JSON文件,将每个注释映射到一个评论。每个评论都有许多评论,但每个评论都属于一个评论 以下是生成JSON文件的控制器:Ruby on rails 未定义的方法`注释';对于nil:NilClass(RubyonRails),ruby-on-rails,ruby,Ruby On Rails,Ruby,在RubyonRails中,我试图呈现一个JSON文件,将每个注释映射到一个评论。每个评论都有许多评论,但每个评论都属于一个评论 以下是生成JSON文件的控制器: reviews: @ship.reviews.preload(:user_profile).map do |review| { id: review.id, body: review.body, rating: review.rating,
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
在这一行:
comments: @review.comment.preload(:comment).map do |comment|
从
@review.comments.preload(:comment).map do | comment
中删除.preload(:comment)
。你根本不需要它。可能是因为@review
没有在reviews:@ship.reviews.preload(:user_profile).map do | review
行中引用review
。尝试删除@
以引用映射范围内的变量。@
是一个类的实例变量。谢谢评论:review.comments.map do | comment |“workedthanks”评论:review.comments.map do | comment |工作
undefined method `comment' for nil:NilClass
comments: @review.comment.preload(:comment).map do |comment|