Rails 4-acts_as_votable,更改默认排序顺序 [英] Rails 4 - acts_as_votable, change default sort order

查看:110
本文介绍了Rails 4-acts_as_votable,更改默认排序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails应用程序,可以在某些模型上投票.在我的一个模型中,我想更改default_scope,以便首先显示投票最多的对象.我在模型文件中尝试了以下方法:

I have a Rails app that allows voting on some models. In one of my models I want to change the default_scope so that objects that has the most votes is displayed first. I have tried the following in my model file:

def self.default_scope
  order('votes_for.size DESC')
end

这给了我以下错误:

SQLite3::SQLException: no such column: votes_for.size: SELECT "solutions".* FROM "solutions"  WHERE "solutions"."competition_id" = ?  ORDER BY votes_for.size DESC

我想知道是否有一种方法可以更改默认的默认排序顺序,但是我正在做的显然不起作用.

I wonder if there is a way the change the default default sort order, what I'm doing is obviously not working.

如果可能的话,使其在控制器级别(不是默认顺序)运行的解决方案也将很好.

Solutions for making it work in the controller level (not default order) would also be nice, if that's possible.

推荐答案

为什么votes_for.size?我假设votes_for是数据库中的属性,它是整数的一种,并保持每条记录的票数.所以应该是votes_for DESC.

Why votes_for.size? I assume votes_for is an attribute in database that is a type of integer and keeps votes count for each record. So it should be votes_for DESC.

class MyModel < ActiveRecord::Base
  default_scope { order('votes_for DESC') } 
end

更新(在发现votes_for是gem中的方法而不是db中的属性之后)

您将必须使用缓存投票: https://github.com/ryanto/acts_as_votable#caching 然后,您可以使用以下方法创建作用域:

You'll have to use caching votes: https://github.com/ryanto/acts_as_votable#caching Then you can create a scope using:

Solution.order(:cached_votes_up => :desc)

default_scope { order(:cached_votes_up => :desc) } 

这篇关于Rails 4-acts_as_votable,更改默认排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆