Trung Tran
Trung Tran

Reputation: 13771

undefined method "each" rails 4.0

I am an error in my view:

undefined method `each' for nil:NilClass
<tbody>
   <% @invoices.each do |invoice| %>
     <tr>
       <td><%= invoice.invoiceDate%></td>
       <td><%= invoice.invoiceNumber %></td>

Here is my invoice controller index:

def index
    @invoices = Invoice.all
end

Most posts I've seen about this error are because @invoices isn't declared correctly, unlike mine. Anyone have any ideas what else might be wrong??

Thanks!!

Upvotes: 1

Views: 4037

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

that belong to that task order

You'll be best doing that like this:

#config/routes.rb
resources :task_orders

#app/controllers/task_orders_controller.rb
Class TaskOrdersController < ApplicationController
   def show
      @task_order = TaskOrder.find params[:id]
      @invoices = @task_order.invoices
   end
end

#app/views/task_orders/show.html.erb
<% for invoice in @invoices do %>
   <%= invoice.something %>
<% end %>

Upvotes: 4

Joe Kennedy
Joe Kennedy

Reputation: 9443

Since you're using @invoices in your show view, you need to actually set @invoices in your show method, rather than your index method. So, add the following code to your controller, and you should be all set.

def show
  @invoices = Invoice.all
end

Upvotes: 5

Related Questions