How to always use a base class and ignore STI in Rails?

I have a module that I include in several models with this content:

self.class.find_by_foo(bar)

Everything was fine until I started using STI. This line should always generate a request

select * from table where foo=bar"

and not

select * from table where foo=bar AND type="Whatever"

Is there an easy way to avoid this?

I mean two solutions. Walk through the class hierarchy until I find the topmost class before ActiveRecord::Baseor run the query manually, for example:

self.class.find_by_sql("select * from #{self.class.table_name} where foo=bar")

I do not like the solution. Is there a better one?

+5
source share
2 answers

First, you can always get to the base class using the base_class method:

self.class.base_class.find_by_foo(bar)

. , Rails :

self.class.where(:foo => bar)

, .

+20

, STI:

klass = self.class
self.class.ancestors.each do |k|
  if k == ActiveRecord::Base
    break # we reached the bottom of this barrel
  end
  if k.is_a? Class
    klass = k
  end
end
+2

All Articles