Sorting model objects in the View - call Model method in View or implement sort in Controller?
By default when I call this:
<table>
<% @question.answers.each do |answer| %>开发者_C百科
<tr>
The answers for a question are displayed in the order they were created.
What's the appropriate way to sort them according to their votes?
I'm not sure whether I need to call a method on the answers in the View or implement a sort function in the Controller or the Model.
If I do it once, I'll do it in the view something like:
<% @questions.sort {|x,y| y.votes <=> x.votes }.each do |question| %>
<p><%= @question.title %></p>
<% end %>
And like cwninja, if there's anything more interesting than that I'll do the logic in the controller or a helper.
It's mostly a matter of style.
Personally:
- If it's a hard coded sort order, just stick it in the view.
- If it has some logic behind it (based on request params, needs pagination or anything else interesting) then stick the collection in an
@answers
variable.
精彩评论