Rails 4 - acts_as_votable, change default sort order

醉酒当歌 提交于 2019-12-08 03:47:17

问题


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.


回答1:


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

update(after finding out that votes_for is a method from gem and not an attribute in db)

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)

or

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


来源:https://stackoverflow.com/questions/24789255/rails-4-acts-as-votable-change-default-sort-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!