Last active
December 14, 2015 12:19
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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' |
Maybe a cleaner solution:
class ActiveRecord::Base
def self.default_scope
order(:id)
end
end
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
I don't like the idea of having a global default scope but if you really need that, you can try something like:
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 needalias_method_chain.