[英]Sort association models in Rails 3?
Menu has_many :dishes. 菜单has_many:菜肴。
I want to sort the dishes by Dish.number. 我想按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 谢谢
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| %>
In your controller: 在你的控制器中:
def list
@dishes = @menu.dishes.all(:order => :number)
end
In your view: 在你看来:
<% @dishes.each do |dish| %>
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: 我不确定我是否理解你要做的事情,但是......要根据它们的数字属性来迭代菜肴,你只需要在菜肴上使用:order选项:
<% @menu.dishes.all(:order => :number).each do |dish| %>
...
<% end %>
您可以使用订单方法:
<% @menu.dishes.order(number: :asc).each do |dish| %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.