开发者

Ordering a table column alphabetically

I have the following code to display any comments that a user has made in a table on the users show page. The code works fine and a table is diplayed with all of the users comments and the permits they belong to. Currently the table displayed shows the permits in the order they were created by the user. I would like to arrange the table so that the permit column is displayed in alphabettical order instead of when they were created. Im not sure if I need to adjust this code or something in the controller.

  <% if @user.comments.exists? then %>

  <b>Comments:</b><br />
  <table>

  <tr>
<th>Permit</th>
<th>Comment</th>
  </tr>

  <% @user.comments.each do开发者_如何学Go |comment| %>

  <tr>
      <td><%= link_to comment.permit.name, comment.permit %></td>
      <td><%= comment.body %></td>
  </tr>
  <% end %>
  </table>
  <% end %>


Use the ActiveRecord order method.

Check the official documentation here: http://guides.rubyonrails.org/active_record_querying.html#ordering

In your case, that would be something like:

<% @user.comments.order('name').each do |comment| %>


 > sorted_permits = @user.permits.sort

This gives you a list of permits, ordered naturally (i.e. if they are String values, they are sorted alphabetically, if they are numeric values, they are sorted from lowest to highest). You can do that in your view, or more typically, in your controller.

So, if I have a list of permits such as:

permits = ["Fishing", "Hunting", "Reading", "Driving"]

Then when I can do the following:

 > permits.sort
=> ["Driving", "Fishing", "Hunting", "Reading"]

NOTE that .sort returns a copy of the list, in sorted order, while the similar .sort! modifies the original list, reordering it permanently (in memory), but does not change the order/IDs of the permits in the database.

See: http://www.ruby-doc.org/core/classes/Array.html#M000244


Using the :order option directly on the relation definition should do the trick:

class Comment < ActiveRecord::Base
  has_many :permits, :order => 'name DESC'
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜