1

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

This gives me the following error:

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.

4

1 回答 1

2

为什么votes_for.size?我假设votes_for是数据库中的一个属性,它是一种整数类型,并保持每条记录的投票计数。所以应该是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 然后您可以使用以下方法创建范围:

Solution.order(:cached_votes_up => :desc)

或者

default_scope { order(:cached_votes_up => :desc) } 
于 2014-07-16T19:55:33.827 回答