Link to home
Start Free TrialLog in
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

ASKER CERTIFIED SOLUTION
Avatar of Andrew Chipman
Andrew Chipman

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial