Philx94
Philx94

Reputation: 1285

undefined method `each' for nil:NilClass error for index

I created a seed which I made sure worked by testing it in the rails console beforehand. Now I am trying show the instance variable @services in my view, but I have an error that says it's nill.

Any ideas?

Thank you

//home.html.erb

  <div>
    <% @services.each do |service| %>
    <%= service.name %>
    <% end %>
  </div>
//services_controller.rb
class ServicesController < ApplicationController
before_action :set_service, only: [:index, :show]

  def index
    @services = Service.all
  end

  def show
    set_service
  end

    private

  def set_service
    @service = Service.find(params[:id])
  end
end
//service.rb

class Service < ApplicationRecord
    validates :name, presence: true
    validates :description, presence: true
    has_many :reviews
end

This is the error that's being rendered

undefined method `each' for nil:NilClass

Upvotes: 0

Views: 91

Answers (2)

shernandez
shernandez

Reputation: 1

Change this code:

before_action :set_service, only: [:index, :show]

To this:

before_action :set_service, only: [:show]

Upvotes: 0

Yaro
Yaro

Reputation: 568

  1. add root URL mapping, and point it to services index action, as in root 'services#index' in config/routes.rb
  2. move content of home.html.erb to views/services/index.html.erb
  3. change before_action :set_service, only: [:index, :show] to before_action :set_service, only: :show

See the comments on question :)

Upvotes: 1

Related Questions