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.
Here is the comment model
Here is the review.rb model
However my json file returns an error: undefined method `comment' for nil:NilClass on this line:
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.