Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding scope to ActiveRecord causes hierarchy error

I've just converted all of my Rails models to use uuid as a primary key replacement, but this breaks the #first and #last methods so I'm trying to add a default scope that sorts by created_at instead of id.

My concern looks like this:

# config/initializers/uuid_support.rb
module 
  extend ActiveSupport::Concern

  included do
    default_scope -> { order 'created_at ASC' }
  end
end
ActiveRecord::Base.send :include, UuidSupport

Once this has been added, the following error gets thrown when performing a fetch on any model: ActiveRecord::ActiveRecordError: ActiveRecord::Base doesn't belong in a hierarchy descending from ActiveRecord.

like image 884
Baub Avatar asked Mar 23 '26 15:03

Baub


1 Answers

Looks like you're trying to create a concern and have your models include it. For that, I recommend a different approach and not do it through an initializer, but rather as an actual concern, the way Rails intended it.

Get rid of your initializer, and put the following code in app/models/concerns/module_name.rb:

module ModuleName # replace with desired name
  extend ActiveSupport::Concern

  included do
    default_scope -> { order 'created_at ASC' }
  end
end

If <= Rails 3, add this to application.rb to load the concerns:

config.autoload_paths += %W(
  #{config.root}/app/models/concerns
)

Include your concern in your models by doing

include ModuleName

at the beginning of your models.

If the reason you did this with an initializer is because you want every model to include this behavior, now is the time to write an initializer.

Either as monkey patch:

# config/initializers/name.rb
class ActiveRecord::Base
  include ModuleName
end

or like you did:

# config/initializers/name.rb
ActiveRecord::Base.send :include, ModuleName
like image 178
weltschmerz Avatar answered Mar 25 '26 08:03

weltschmerz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!