views:

15

answers:

3

Menu has_many :dishes.

I want to sort the dishes by Dish.number.

Currently in my view it looks like:

<table class="menu">
  <% @menu.dishes.each do |dish| %>
    <div class="dish">
      <tr>
        <td>
          <div class="dish_div dish_name">
            <% if @menu.name != 'Övrigt' && @menu.name != 'Box to go' %>
              <span class="dish_name"><%= "#{dish.number}. #{dish.name}" %></span>
            <% else %>
              <span class="dish_name"><%= "#{dish.name}" %></span>
            <% end %>

            <% if dish.strength_id == 2 %>
              <%= image_tag('chili.png') %>
            <% elsif dish.strength_id == 3 %>
              <%= image_tag('chili.png') %>
              <%= image_tag('chili.png') %>
            <% elsif dish.strength_id == 4 %>
              <%= image_tag('chili.png') %>
              <%= image_tag('chili.png') %>
              <%= image_tag('chili.png') %>
            <% end %>
          </div>
          <div class="dish_div"><%= "#{dish.description}" %></div>
          <div class="dish_div dish_price"><%= "#{dish.price} kr" %></div>
        </td>
      </tr>
    </div>
  <% end %>
</table>

How do I do that?

Should it be in the view or controller?

Thanks

+1  A: 

In your controller:

def list
  @dishes = @menu.dishes.all(:order => :number)
end

In your view:

<% @dishes.each do |dish| %>
Daniel Vandersluis
+1  A: 

I'm not sure if I understood what you're trying to do, but … to iterate the dishes sorted by their number attribute, you just need to use the :order option on the dishes:

<% @menu.dishes.all(:order => :number).each do |dish| %>
  ...
<% end %>
Andreas
A: 

Neither! :) --- do it in your model definitions

If you always want to order on strength:

class Menu
  has_many :dishes, :order=>'strength_id DESC'
end

class Dish
  belongs_to :menu
end

Otherwise, just order in the view:

<% @menu.dishes.sort_by{|dish| dish.strength_id}.each do |dish| %>
Jesse Wolgamott