Looking for a way to alphabetize the display of a table in Rails?
I've got two models, Character and Skills. I'm looking for a way to automatically sort all skills by skill.name in the view.
Here's some code from my view:
<h2><%= @character.name %>'s Skills</h2>
<% @character.skills.reject {|skill| skill.new_record? }.each do |skill| %>
<b><%= skill.name %></b><br /><br />
...
<%= skill.ranks %><br />
<%= link_to 'Edit', edit_character_skill_path(@character, skill) %>
<br /><br />
<% end %>
And here's the code from my controller:
def index
@character = Character.find(params[:character_id])
@skill = @character.skills.build
@skills = @character.skills.find(:all, :order => 'name')
end
I'm not sure the last bit will actually work, and I'm not sure how to call it in the view if it DOES work. Any input? Als开发者_C百科o, this will alphabetize new instances of skill, right? As in, I have skill A and skill D, then add skill B, it will display as A, B, D? Thanks!
You can take the array of skills, and just do .sort
So, if you had a character, where @character.skills
was:
@character.skills
=> ["Archery", "Magic", "Sneak", "Combat", "Healing", "Repair", "Fishing"]
You could do:
@sorted_skills = @character.skills.sort
=> ["Archery", "Combat", "Fishing", "Healing", "Magic", "Repair", "Sneak"]
Doing this sets sorted_skills
to the naturally ordered array of skills, but does NOT alter the original order of @character.skills
. However, if you instead called @character.skills.sort!
(note the !
), it WOULD sort, and permanently change the order of the array in @character.skills (at least until that variable goes out of scope). .sort!
does not alter the model, or data in the database in any way.
You can also .sort
any array, say of integers, and Ruby will sort them in an intelligent way. There's even more to it than that, but it sounds like this should cover your needs.
Ruby documentation for Array class
精彩评论