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

时间:2019-11-30 02:58:40

标签: ruby-on-rails ruby

在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|

1 个答案:

答案 0 :(得分:0)

.preload(:commment)中删除@review.comments.preload(:comment).map do |comment|。您根本不需要它。