alexjs000
alexjs000

Reputation: 85

NoMethodError in StaticPages#home when attempting to list database query

Ruby noob here, I created a search form and I am trying to query a db and display the results. I am getting NoMethodError in StaticPages#home along with.... /home/action/Projects/CodonCoderTest5/app/views/static_pages/home.html.erb where line #4 raised:

undefined method `each' for nil:NilClass

Where am I going wrong?

layouts/StaticPages/home

<h1>StaticPages#home</h1>
<% @data_bases.each do |list| %>
     <div class="list">
         <h1 class="list-mrnaCodon"><%= link_to list.mrnaCodon %></h1>
     </div>
<% end %>

controller

class DataBaseController < ApplicationController

  def new
  end

  def index
     if params[:search]
         @data_bases = Match.search(params[:search]).order("created_at DESC")
     else
         @data_bases = Match.order("created_at DESC")
     end
  end
end

Upvotes: 1

Views: 137

Answers (1)

Rob Mulholand
Rob Mulholand

Reputation: 899

The error means that @data_bases in your view is evaluating to nil. That makes sense, since the only way the view for StaticPages#home would have access to that variable is if it were set in the corresponding controller action (i.e. the home method on the StaticPagesController). Looks like you're only setting that variable on the DataBaseController.

class StaticPagesController < ApplicationController

  ...

  def home
    if params[:search]
      @data_bases = Match.search(params[:search]).order("created_at DESC")
    else
      @data_bases = Match.order("created_at DESC")
    end
  end

  ...

end

Upvotes: 1

Related Questions