I have a Ruby array which contains Post objects (a Mongoid model) with a created_at method returning a Time object. What I want is to sort that array using that method (which is present on every element on the array). I tried @posts.sort_by {|post| post.created_at} but that didn’t work. How could I achieve this? Thanks!
EDIT: Example of the array:
[#<Post _id: 4ffd5184e47512e60b000003, _type: nil, created_at: 2012-07-11 10:12:20 UTC, title: "TestSecond", description: "TestSecond", slug: "assa", user_id: 4ffc4fd8e47512aa14000003>, #<Post _id: 4ffd518ee47512e60b000004, _type: nil, created_at: 2012-07-11 10:12:30 UTC, title: "TestFirst", description: "TestFirst", slug: "assadd", user_id: 4ffc4fd8e47512aa14000003>].
EDIT #2: I’m getting that @posts arra with:
@posts = Array.new
@user.following.each do |user|
user.posts.each do |p|
@posts << p
end
end
I’m not sure why you have an array here. Normally, with Mongoid querying, you should have a
Mongoid::Criteriainstance, which you candesc(:created_by)orasc(:created_by)on, in order to sort.Still, can’t think of any reason
sort_bydoesn’t work for properly for you, works great on my app (just tried at console).UPD:
Well, to still have a mongoid collection there, something like this might be done:
Now, you can
@posts.desc(:created_at).UPD2:
Also, for purpose of having a cleaner code, you could define a
posts_from_followingonUser:and then, just do
in your controller.