ruby-on-railsrubyruby-on-rails-4default-scope

Rails 4 - acts_as_votable, change default sort order


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.


Solution

  • 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) }