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?)