I have a series of users who each make numerous posts (and the posts receive “views”), and I have sorted them in various ways in the past.
For example, here is the 8 most viewed users:
@most_viewed = User.sort_by{|user| user.views}
And then in my model, user.rb file:
def views
self.posts.sum(:views) || 0
end
This worked fine in the past.
The problem is that my sorting used the sort_by method, which doesn’t play nice with the will_paginate gem because it returns an Array instead of a Relation.
How can I do the following things in Rails 3, Active Record Relation, Lazy Loading style? For example, as named scopes?
- Users with at least one post
- Users with the greatest number of total views on their posts
- Users with the posts with the greatest number of views (not total)
- Users with the most recent posts
- Users with the most number of posts
You can still paginate an array, but you will have to require ‘will_paginate/array’
To do this, you could create a file (i.e.: “will_paginate_array_fix.rb”) in your config/initializers directory. Add this as only line in that file:
restart your server, and you should be able to paginate normal ruby arrays.
you should use the order method. This will perform the sorting through SQL, which give better performance in the first place 🙂
or for ascending order
This will return a relation, so you can add other stuff such as where clauses, scoping, etc..
For an ordered list of users who’s name start with r
visit http://guides.rubyonrails.org/active_record_querying.html for the official explanation