Skip to content

Instantly share code, notes, and snippets.

@blasterpal
Last active December 14, 2015 12:19
Show Gist options
  • Select an option

  • Save blasterpal/5085761 to your computer and use it in GitHub Desktop.

Select an option

Save blasterpal/5085761 to your computer and use it in GitHub Desktop.
default_scope for MySQL to PostgreSQL project migration. The id sort order is not == when compared to MySQL and many specs are failing, even some relating to Gem models.
# Needed because I also have Gem models that are throwing errors not just my models. I'd like to have one simple mixin or monkey patch.
# without mucking with ActiveRecord::Base too much.
module SortedById
extend ActiveSupport::Concern
included do
default_scope order('id ASC')
end
end
ActiveRecord::Base.send(:include,SortedById)
# Oh Noes!!!
#ruby/1.9.1/gems/activerecord-3.2.11/lib/active_record/model_schema.rb:148:in `reset_table_name': undefined method `abstract_class?' for Object:Class (NoMethodError)
#from /Users/hankbeaver/blinqmedia/blinq_ad_manager/local/ruby/1.9.1/gems/activerecord-3.2.11/lib/active_record/model_schema.rb:104:in `table_name'
@sobrinho

sobrinho commented Mar 4, 2013

Copy link
Copy Markdown

I don't like the idea of having a global default scope but if you really need that, you can try something like:

class ActiveRecord::Base
  def self.inherited(klass)
    klass.default_scope order('id ASC')
  end
end

This will call the default scope on each inherited class instead of the base itself (it needs to be loaded before any model).

I'm not sure if active record already do something on Class.inherited, you may need alias_method_chain.

@sobrinho

sobrinho commented Mar 4, 2013

Copy link
Copy Markdown

Maybe a cleaner solution:

class ActiveRecord::Base
  def self.default_scope
    order(:id)
  end
end

@blasterpal

Copy link
Copy Markdown
Author

I tried a monkey patch as a well as creating my own base class that extends ActiveRecord::Base. The former, still threw the abstract_class? exception and the latter could not introspect the table name of the model anymore and asked for me to self.table_name = ?. Trying another route. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment