开发者

sorting an association

my question is -- how can I apply an order to the tags in this view? The "default_scope" in Tag.rb doesn't work here.

View

<% @skills.each do |s| %>      
  <ul>
    <% s.active_positions.collect{|p| p.tags}.flatten.uniq.each do |tag| %>
    <li><%= link_to tag.name, s %></li>
    <% end %>
  </ul>
<% end %>

Controller

@skills = Skill.includes(:active_positions => :tags)

Models

class Skill
  has_many :tags
  has_many :positions
  has_many :active_positions, :class_name => "Position", :conditions => {:hidden => false}
end

class Position
  belongs_to :skill
  has_and_belongs_to_many :tags
end

class Tag
  belongs_to :skill
  has_and_belongs_to_many :positions  
  default_scope :order => "sequence ASC"
end

SOLUTION

in the view...

<% s.active_positions.collect{|p| p.tags}.flatten.uniq.sort开发者_Go百科_by{|tag|tag.sequence}.each do |tag| %>


You can sort arrays using sort! and/or sort_by! You can pass it a block like so:

@something.to_a.sort_by!{ |entry| entry.attribute }.each ...

In your case, this should be something like:

<% s.active_positions.collect{|p| p.tags}.flatten.uniq.sort_by{ |tag| tag.name }.each do |tag| %>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜