undefined method for nil:NilClass

Andrew Chipman
Andrew Chipman used Ask the Experts™
on
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

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
comments: review.comments.map do |comment|

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial