简体   繁体   中英

undefined method `each' for nil:NilClass - Ruby on Rails

I'm trying to modify a web app in rails and it throws the error

undefined method `each' for nil:NilClass

in - @movies.each do |movie|

Here is the index html haml file

 %h1 All Movies
    = form_tag movies_path, :id=>"ratings_form", :method => :get do
      Include:
      - @all_ratings.each do |rating|
        = rating
        = check_box_tag "ratings[#{rating}]",1, (true if @ratings[rating]), :id=>"ratings_#{rating}."
      = submit_tag 'Refresh', {:id=>"ratings_submit"}

    %table#movies
      %thead
        %tr
          %th{:class=>("hilite" if @sort_by =="title")}= link_to 'Movie Title', movies_path(:sort_by=>"title", :ratings=>@ratings), :id=>"title_header"     
          %th Rating
          %th{:class=>("hilite" if @sort_by =="release_date")}= link_to 'Release Date', movies_path(:sort_by=>"release_date", :ratings=>@ratings), :id=>"release_date_header"
          %th More Info
      %tbody
        - @movies.each do |movie|
          %tr
            %td= movie.title 
            %td= movie.rating
            %td= movie.release_date
            %td= link_to "More about #{movie.title}", movie_path(movie)

    = link_to 'Add new movie', new_movie_path

Here is the index fun in the controller.rb file

def index
     @all_ratings = Movie.all_ratings
     redirect = false

     logger.debug(session.inspect)

         if params[:sort_by]
          @sort_by = params[:sort_by]
          session[:sort_by] = params[:sort_by]
        elsif session[:sort_by]
          @sort_by = session[:sort_by]
          redirect = true
        else
          @sort_by = nil
        end

        if params[:commit] == "Refresh" and params[:rating].nil?
          @ratings = nil
          session[:ratings] = nil
        elsif params[:ratings]
          @ratings = params[:ratings]
          session[:ratings] = params[:ratings]
        elsif session[:ratings]
          @ratings = session[:ratings]
          redirect = true
        else
          @ratings = nil
        end

        if redirect
          flash.keep
          redirect_to movies_path :sort_by=>@sort_by, :ratings=>@ratings
        end    

        if @ratings and @sort_by
          @movies = Movie.where(:rating => @ratings.keys).order(@sort_by)
        elsif @ratings
          @movies = Movie.where(:rating => @ratings.keys)
        elsif @sort_by
          @movies = Movie.order(@sort_by)
        else 
          @movie = Movie.all
        end

        if !@ratings
          @ratings = Hash.new
        end
      end

Where is the error?

Replace @movie = Movie.all for @movies = Movie.all . It's at the bottom of your index controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM