0
votes

I'm having trouble working around a default_scope in an STI situation. Is there any way to prevent a default_scope from existing in a child class or overwriting query conditions?

class Parent < ActiveRecord::Base
  default_scope where(:type => ["Child", "OtherChild"])
  scope :flag, where(:flag => true)
end

class Child < Parent
end

class OtherChild < Parent
end

Parent.all => Produces the correct results, all Child and OtherChild items are returned. It doesn't return objects with the 'RemovedChild' type, which no longer has a model in the system.

Child.all => Produces the correct results, all Child results.

Child.flag.all => Broken, instead of all Child's with flag = true it returns the same results as Parent.flag.all, adding the default_scope from the Parent class which replaces the type = Child that the Child class adds.

I have to assume the Parent table will include items with a type that don't correspond to a currently-available class which is what my default scope was trying to solve. If there's a way to globally catch and ignore any instances of ActiveRecord::SubclassNotFound that would work as well.

1
try: scope :flag -> {where(flag:true)}, I believe that by not using a lambda, you are not resolving the scope at the correct time (i.e. when you call it instead of when you define it)ilan berci
No luck, I switched to scope :flag, lambda { where(:flag => true) } and got the same results.bamnet

1 Answers

1
votes

To delay the scope resolution and workaround this you can switch to defining a class method instead of a scope.

class Parent < ActiveRecord::Base
  default_scope where(:type => ["Child", "OtherChild"])
  def self.flag
    where(:flag => true)
  end
end