Avatar of Andrew Chipman
Andrew Chipman
 asked on

undefined method for nil:NilClass

In ruby on rails I'm trying to render a json file that will map each comment to a review. Each Review has many comments but each comment belongs to a review.

Here is my controller to generate a json file.

`  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.comment.preload(:comment).map do |comment|
            {
              id: comment.id,
              body: comment.body,
              user_profile: comment.user_profile_id,
            }
          end
        }

Open in new window


Here is the comment model

class Comment < ApplicationRecord
  belongs_to :user_profile
  belongs_to :review
end

Open in new window


Here is the review.rb model

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

Open in new window


However my json file returns an error: undefined method `comment' for nil:NilClass on this line:

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

Open in new window

JSONRuby

Avatar of undefined
Last Comment
Andrew Chipman

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Andrew Chipman

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck