user3110815 user3110815 - 5 months ago 9
Ruby Question

Loop through rails associations

1)I'm trying to create a site that has several restaurants each having their own unique menu being displayed in a table, the association works in the console but not in code.I loop over the @restaurant instance variable then in the table I put the data I want from the menu so restaurant.menu.dish but getting an error that 'each' is undefined even though I didn't state a one-one relationship.How may I carry out the desired behavior?

2) How do I ensure that the menu data corresponds with the right restaurant,I'm assuming that the show controller saves the restaurant variable with a specific ID and calling a method like .dish would know what restaurant based on the show action variable, is this correct thinking?

Restaurant Model

class Restaurant < ActiveRecord::Base

has_attached_file :thumbnail, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :thumbnail, content_type: /\Aimage\/.*\Z/
has_many :menus

def self.search(search)
if search
@restaurants= Restaurant.where("name LIKE ?", "%#{search}%")
else
@restaurants=Restaurant.all
end
end
end


Menu Model

class Menu < ActiveRecord::Base
belongs_to :restaurant
end


Restaurant controller with show action

def show
@restaurant = Restaurant.find(params[:id])
end


Show.html.erb

<div class="col-md-8">
<table class="table table-striped">
<h3>Menu</h3>
<thead><tr><th>Dish</th><th>Price</th><th>Calories</th></tr></thead>
<tbody>
<%= @restaurant.each do |restaurant| %>
<tr>
<td><%= restaurant.menu.dish %></td>
<td><%= restaurant.menu.price %></td>
<td><%= restaurant.menu.price %></td>
</tr>
<tr><td>..</td><td>..</td><td>..</td></tr>
<% end %>
</tbody>
</table>
</div>

Answer

You are showing restaurant, that has many menus, right? Here we go:

<%= @restaurant.menus.each do |menu| %>
  <tr>
     <td><%= menu.dish %></td>
     <td><%= menu.price %></td>
  </tr>
  <tr><td>..</td><td>..</td><td>..</td></tr>
<% end %>
Comments