My task is to display user comments on the main page. And it is also desirable to display the product to which comments were left.

When I display the following code in the form:

View -> form

<h2>What others felt about this:<h2> <% @product.reviews.reverse.each do |review|%> <p> <%= review.content%> Posted <%=time_ago_in_words(review.created_at)%> ago by <%=review.client.name%></p> 

then everything works fine. Next, I will show a couple of methods in this class: Reviews controller:

 def create @product =Product.find params[:product_id] @review = @product.reviews.new(review_params) @review.client_id = @current_client.id @review.save respond_to do |format| format.html {redirect_to @product} end end private def review_params params.require(:review).permit(:content, :product_id, :client_id, :stars) end 

But when I try to display these comments on the main page:

 <div class="item active"> <% @product.reviews.reverse.each do |review|%> <p> <%= review.content%> Posted <%=time_ago_in_words(review.created_at)%> ago by <%=review.client.name%></p> </div> 

That says review = nil. Error: undefined method `reviews' for nil: NilClass

What I need to change is to display a comment on the main page and preferably a product image. product.picture

Thank you in advance!

  • Put a minus for the next "debug my code for me, please." Use the debugger! Find out if exactly the objects you expect are everywhere! But if you ask for help, if possible (and here it is clearly there) quote the error message. - D-side
  • I quoted the message. I thought it was just that the error was clear from my comment. I just do not understand why this method is not visible if it is visible and works well in the form. - Alex
  • Oh yeah. That's why I asked for the message. nil not review . And what is caused by the reviews , i.e. @product . And I really do not see in the question the code that sets it for the main one. - D-side
  • I have this confusion. why in the form everything is fine with the reviews, but on the main one - no - Alex
  • Because @product is not set on the main one, obviously. - D-side

1 answer 1

Define the @product variable in your main page controller action and everything will work. Now @product is nil.