Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort association models in Rails 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

like image 416
never_had_a_name Avatar asked Nov 30 '22 10:11

never_had_a_name


2 Answers

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| %>
like image 136
Jesse Wolgamott Avatar answered Dec 05 '22 01:12

Jesse Wolgamott


In your controller:

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

In your view:

<% @dishes.each do |dish| %>
like image 37
Daniel Vandersluis Avatar answered Dec 05 '22 02:12

Daniel Vandersluis