在Rails 3中排序关联模型?

nev*_*ame 4 ruby-on-rails

菜单has_many:菜肴.

我想按Dish.number排序菜肴.

目前在我看来它看起来像:

<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>
Run Code Online (Sandbox Code Playgroud)

我怎么做?

它应该在视图还是控制器中?

谢谢

Jes*_*ott 15

都不是!:) ---在您的模型定义中执行此操作

如果您总是想要强力订购:

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

class Dish
  belongs_to :menu
end
Run Code Online (Sandbox Code Playgroud)

否则,只需在视图中订购:

<% @menu.dishes.sort_by{|dish| dish.strength_id}.each do |dish| %>
Run Code Online (Sandbox Code Playgroud)