i have rails method to sort the blogs based on their votes (acts_as_votable).
The method is
# @allblogs will be some filtered blogs array
@fetch = []
@most_effective_votes = []
for blog in @allblogs
@most_effective_votes << [blog.id,blog.votes_for]
end
@most_effective_votes = @most_effective_votes.sort{|a,b| a[1]<=> b[1]}.Reverse
for mev in @most_effective_votes
@fetch << blog.Find(mev[0])
end
@allblogs = @fetch.Paginate(:per_page => 10,:page=>params[:page])
How to reduce these many number of lines and to change this to some namedscope . Please give some suggestions.
I think must of what you are trying to do can be done with a query without the need of doing operations with arrays.
First of all, @allblogs should be a scope, not a filtered array.
Second, it sames you can change all of what you were doing by using:
Blog.order("DESC votes_for")
So your named_scope would be:
class Blog < ActiveRecord::Base
scope :with_most_votes, order("votes_for DESC")
end
And @fetch would be @allblogs.with_most_votes.
Let me know if you need more help.