Aaditya rathore
Aaditya rathore

Reputation: 93

ActionView::Template::Error (undefined method `each' for nil:NilClass):?

I've a services model in my ruby on rails project but I'm unable to render it in pages#home view of my project I'm getting this undefined method `each' for nil:NilClass Although I've defined the variable in my Servicecontroller-

My ServicesController file-

class ServicesController < ApplicationController
  def show
    @services = Service.all
  end
end

My show file-

<div class="container">

  <h3>Services we offer-</h3>
  <% @services.each do |service| %>
        <h5><%= service.name %></h5>
        <p><%= service.description %></p>
  <% end %>
</div>

and the path of my show file of services view is this- app\views\services\_show.html.erb and I'm rendering it in my pages views app\views\pages\home.html.erb as <%= render 'services/show' %>, I'm still getting the error although I'm able to see all services in rails console using @services=Service.all command.

Can somebody help me out here?

Upvotes: 1

Views: 2603

Answers (1)

gd_silva
gd_silva

Reputation: 1025

You're setting the variable in the wrong controller and action.

If you want the @services instance variable to be available in the home.html.erb view, you'll need to set that data in PagesController#home.

If you set the variable in the correct action and then render a partial inside the home view, beit _show or another one, you'll be able to access that variable.

Try something like:

class PagesController < ApplicationController
  ...

  def home
    @services = Service.all
  end
end

Upvotes: 3

Related Questions