简体   繁体   中英

Rails acts_as_votable gem ordering

I new in Rails framework. I used acts_as_votable gem and will_paginate gem. When I wanna order the articles by upvote but it doesn't work. I used acts_as_votable's get_likes method for order but I failed. I'm really stuck.

Article Model:

default_scope  { order(get_likes: :desc) }

after that I get Statementİnvalid error .

Your get_likes - method will not work with an order-scope, because the sort order is executed on the database and your method's data is unknown to the database.

You could sort your records in ruby, using array methods, but that is slow and this operation should be done at database level.

By using counter-caches which store the number of counts for a record in a column you can sort in the database. The acts_as_votable gem already offers counter-cache implementations .

You just need to add the migration of the column you need to the database. Here the coulmn from their docs:

add_column :posts, :cached_votes_total, :integer, :default => 0

Afterwards you can sort with the order scope.

Post.order(:cached_votes_total=> :desc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM