简体   繁体   English

Rails act_as_votable宝石排序

[英]Rails acts_as_votable gem ordering

I new in Rails framework. 我是Rails框架的新手。 I used acts_as_votable gem and will_paginate gem. 我使用acts_as_votable gem和will_paginate gem。 When I wanna order the articles by upvote but it doesn't work. 当我想通过upvote order articles但不起作用时。 I used acts_as_votable's get_likes method for order but I failed. 我使用acts_as_votable的get_likes方法进行订购,但失败了。 I'm really stuck. 我真的被卡住了。

Article Model: 文章模型:

default_scope  { order(get_likes: :desc) }

after that I get Statementİnvalid error . 之后,我得到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. 您的get_likes方法将不适用于订单范围,因为排序顺序是在数据库上执行的,并且数据库中未知您方法的数据。

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 . actions_as_votable gem已经提供了反缓存实现

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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