I have a Post, Reply and a Vote model (polymorphic):
create_table "posts", :force => true do |t|
t.text "content", :limit => 255
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "title"
t.integer "replies_count", :default => 0, :null => false
t.integer "category_id"
end
create_table "replies", :force => true do |t|
t.text "content"
t.integer "post_id"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "votes", :force => true do |t|
t.integer "votable_id"
t.string "votable_type"
t.integer "user_id"
t.integer "polarity"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
I needed the total_votes of posts and replies so I created an instance method:
post.rb and reply.rb:
def total_votes
self.votes.map {|v| v.polarity }.sum
end
So I can use it to sort posts and replies:
homepage:
default_order = "created_at DESC"
params[:order_by] ||= default_order
@feed_items = @post.replies.paginate(page: params[:page],
per_page: 10).order(params[:order_by])
So now, I’m not very sure what do add after order_by in the view:
<span><%= link_to 'total_votes DESC', root_path(order_by: HERE) %></span>
I tried &:total_votes DESC and total_votes DESC but didn’t work.
What’s the right way of doing this? (I thought it was a bit of unnecessary to add a total_votes column to both posts and replies tables, but not sure if that is better for performance?)
I would start with using the database to do the summing for you, but this is a little bit tricky because you need to order by a value that is calculated (an “aggregate”), but let’s set that aside.
Your view will display items in the order determined when the instance variable is set in the controller. So in the controller, you may detect that there’s an
order_byparameter (e.g./feed?order_by=total_votes, and load the@feed_itemsaccordingly, e.g.then in your view, to change the sort order, create a
link_tothat adds the query string parameter (see the last example in the link_to api doc, e.g.Your other question is about how to do the sorting by votes. This answer may provide a good start for that, and an answer to your performance question: Rails: Order by sum of two columns