0

For some weird reason, associations in my list view is not working consistently. In my models I have:

Class Restaurant  < ActiveRecord::Base
has_many  :menus

Class Menu < ActiveRecord::Base
Belongs_to  :restaurant

In my controller I have:

def list
    @menus = Menu.order("menus.id ASC")
end

In my view I have:

<% = menus.each do |menu| %>
    <h4><%= menu.restaurant.name %></h4>
<% end %>

I am getting undefined method “name” . name is a column in the restaurant table.

However, it works in my show view when I use < %= @menu.restaurant.name % > with no problem.

I am using rails 3.2.9 and ruby 1.9.3

4

2 回答 2

1

As Marek Lipka said, you have Menu that are not linked to restaurant.

So reference to menu.restaurant is nil.

If it is intended to have menu without restaurant, you can bypass Nil reference in your view :

<%= menu.restaurant.try(:name) %>

http://apidock.com/rails/Object/try

于 2013-07-29T11:43:20.303 回答
0

At least one of your @menus probably doesn't have its associated restaurant.

Try typing in your console Menu.includes(:restaurant).each{|m| puts m.id unless m.restaurant} to see what menu record(s) cause this problem.

于 2013-07-29T11:30:14.270 回答