Rails ActiveRecord: selecting and sorting on a dynamic field
I have two models, one is Group, the other Item.
A group has many items.
I'm trying to run a query on groups, and return the number of items for each group as a method of the group object.
The view should be :
<% @groups.each do |group| %>
<tr><td><%= group.name %></td><td><%=开发者_高级运维 group.items_count %></td> ... and other fields
<% end %>
I'd like to be able to do a Group.where().page call including the dynamic attribute items_count, and be able to sort results by item_count, just as a standard attribute from the sql table. how can I do that in a simple way ?
The easiest way is probably to fetch the groups you need without a specific ordering, and then sort them in your controller afterwards:
def my_action
@groups = Group.all() # or Group.where(...) for more specific filtering
@groups.sort! { |g1, g2| g1.items_count <=> g2.items_count }
...
end
精彩评论