Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class MyBase < ActiveRecord::Base
def self.compute_type(type_name)
case type_name
when "MyBase"; MyBase
when "Foo"; Foo
when "Bar"; Bar
else super
end
end
end
class Foo < MyBase
end
class Bar < MyBase
end
@tompave

This comment has been minimized.

Copy link

commented Jun 23, 2014

I've tried it, but it seems that that neither compute_type nor find_sti_class are actually being used. Is this message sent only in specific contexts?

I'm working with Rails 3.2.18 and my STI tree is:

User
 ├ Admin
 └ ConsumerUser
    ├ Customer
    ├ Provider
    └ Applicant

I've declared it as:

class User < ActiveRecord::Base

protected
  def self.compute_type(type_name)
    puts "test"
    # case block
  end
end
@charliesome

This comment has been minimized.

Copy link
Owner Author

commented Jun 23, 2014

According to @pixeltrix, if ActiveRecord::Base.store_full_sti_class is true, then Rails will not call compute_type (but it will call find_sti_class, which you've said isn't being called... odd)

@tompave

This comment has been minimized.

Copy link

commented Jun 24, 2014

Ok, thank you, this works:

ActiveRecord::Base.store_full_sti_class = false # was true
User.last # will use the customized User.compute_type

Apparently, this might be what was preventing compute_type from being called.

I can also confirm that find_sti_class is being called. I just made a mistake and re-declared it as an instance method instead of class method. No wonder it wasn't being called.

@tompave

This comment has been minimized.

Copy link

commented Jun 24, 2014

Anyway, ActiveSupport::Dependencies.constantize(type_name) isn't so bad.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.