简体   繁体   English

nil:NilClass 的未定义方法“comment”(ruby on rails)

[英]undefined method `comment' for nil:NilClass (ruby on rails)

In Ruby on Rails I'm trying to render a JSON file that will map each comment to a review.在 Ruby on Rails 中,我试图呈现一个 JSON 文件,它将每个评论映射到评论。 Each review has many comments but each comment belongs to a review.每个评论都有很多评论,但每个评论都属于一个评论。

Here is my controller to generate a JSON file:这是我生成 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
        }

Here is the comment model:这是评论模型:

class Comment < ApplicationRecord
  belongs_to :user_profile
  belongs_to :review
end

Here is the review.rb model:这是 review.rb 模型:

class Review < ApplicationRecord
  belongs_to :user_profile
  belongs_to :ship
  has_many :comments
  has_many :helpfuls
end

However my JSON file returns an error:但是我的 JSON 文件返回错误:

undefined method `comment' for nil:NilClass

on this line:在这一行:

comments: @review.comment.preload(:comment).map do |comment|

Remove .preload(:commment) from @review.comments.preload(:comment).map do |comment|从 @review.comments.preload(:comment).map 中删除.preload(:commment) @review.comments.preload(:comment).map do |comment| . . You don't need it at all.你根本不需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM