正在寻找一种在 Rails 中按字母顺序显示表格的方法?
我有两个模型,角色和技能。我正在寻找一种方法来自动按视图中的技能名称对所有技能进行排序。
这是我的一些代码:
<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 %>
这是我的控制器的代码:
def index
@character = Character.find(params[:character_id])
@skill = @character.skills.build
@skills = @character.skills.find(:all, :order => 'name')
end
我不确定最后一点是否真的有效,并且我不确定如何在视图中调用它(如果它确实有效)。有什么意见吗?另外,这会按字母顺序排列新的技能实例,对吗?比如我有技能A和技能D,然后添加技能B,会显示为A、B、D吗?谢谢!
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? Also, 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以获取技能数组,然后执行
.sort
因此,如果您有一个角色,其中
@character.skills
是:您可以这样做:
执行此操作会 < code>sorted_skills 为自然排序的技能数组,但不会改变
@character.skills
的原始顺序。但是,如果您改为调用@character.skills.sort!
(注意!
),它会排序,并永久更改 @character.skills 中数组的顺序(至少直到该变量超出范围)。.sort!
不会以任何方式改变模型或数据库中的数据。您还可以
.sort
任何数组(例如整数),Ruby 会以智能方式对它们进行排序。还有更多的东西,但听起来这应该可以满足您的需求。Array 类的 Ruby 文档
You can take the array of skills, and just do
.sort
So, if you had a character, where
@character.skills
was:You could do:
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