troubleshooting Question

undefined method for nil:NilClass

Avatar of Andrew Chipman
Andrew Chipman asked on
RubyJSON
1 Comment1 Solution193 ViewsLast Modified:
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
        }

Here is the comment model

class Comment < ApplicationRecord
  belongs_to :user_profile
  belongs_to :review
end

Here is the review.rb model

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

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

comments: @review.comment.preload(:comment).map do |comment|
ASKER CERTIFIED SOLUTION
Andrew Chipman

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 1 Comment.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 1 Comment.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros