I was following this tutorial that shows you how to sort an array. My action looked like this:
def index
@articles = NodeType.find(1).nodes + NodeType.find(2).nodes
@articles.sort_by { |article| article.updated_at }
end
But that didn't work! It wasn't sorting at all.. at least as far as I could tell. Strange, because this worked:
def index
@articles = NodeType.find(1).nodes + NodeType.find(2).nodes
@articles = @articles.sort_by { |article| article.updated_at }
end
It seems you have to assign it to an object first, before returning it.
Subscribe to:
Post Comments (Atom)
3 comments:
Because sort_by returns the new (sorted) array, not modifies it inplace. Just like sort does.
You could instead use the sort! method, like this:
@articles.sort! {|a1,a2| a1.updated_at <=> a2.updated_at}
Hehe.. and here I was trying out "sort_by!"
Thanks ... it helped a lot.
Post a Comment