Home > front end >  "undefined method `each' for nil:NilClass" when I try to display reviews for a specif
"undefined method `each' for nil:NilClass" when I try to display reviews for a specif

Time:10-22

I am building an app in Ruby on Rails where an event is displayed, and when a user clicks on a button under that event, they are redirected to a page that displays all the reviews for that event. I am running into a bit of trouble, though. When I click the button, I am redirected to "events/:id/reviews" and I receive an error that says "undefined method `each' for nil:NilClass". I am confused because to me my index method in my reviews controller and my route in my events show view both look correct. Reviews Controller:

class ReviewsController < ApplicationController
    before_action :redirect_if_not_logged_in
    
    def new
        if @event = Event.find_by_id(params[:event_id])
        @event = @event.reviews.build
        else
            @review = Review.new
        end
    end

    def create
        @review = current_user.reviews.build(review_params)
        if @review.save
        redirect_to review_path(@review)
        else
          render :new
        end
    end

    def show
        @review = Review.find_by_id(params[:id])
    end


    def index
        if @event = Event.find_by_id(params[:event_id])
            @events = @event.reviews
        else
        @reviews = Review.all
    end
end
    private

    def review_params
        params.require(:review). permit(:event_id, :content, :stars)
    end
end

events - show.html.erb

<header class="py-10 bg-blue-200 text-black text-5xl font-caveat text-center"><%= @event.name %></header>
<br></br>


<div>
  <p><%= @event.description %></p>
</div>


<%= link_to "Edit #{@event.name}", edit_event_path(@event) if @event.user == current_user%>

<br></br>

<%= link_to "See All Reviews for #{@event.name}", event_reviews_path(@event) %>

<%= link_to "See who is attending #{@event.name}", event_rsvps_path(@event) %>

Does anybody understand what I am doing wrong here? Thank you

CodePudding user response:

The error is here:

def index
    if @event = Event.find_by_id(params[:event_id])
        # This is the error, this set the variable @events
        # @events = @event.reviews
        # the correct variable should be @reviews
        @reviews = @event.reviews
    else
        @reviews = Review.all
    end
end
  • Related