1
votes

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?

1
If you want to set the instance variable @services = Service.allwhen the request is being processed by PagesController#home you need to actually set the instance variable in that method. Setting an instance variable in another controller does absolutely nothing. And show in rails shows a single record. index corresponds to a collection of records. - max
Thank you It worked, I moved @services=Service.all in my pagesconroller and it worked. Thanks - Aaditya rathore

1 Answers

3
votes

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