2

Slightly simplified, I have the following code:

class MediaFile < ActiveRecord::Base
  has_one    :default_service, ->(m){where(type: _get_service_type(m)))}, :class_name => "Service"
  #...
end

where Service is an STI model with a few different subclasses. The _get_service_type method is shorthanded here for the actual code in my app, but it simply generates the String corresponding to the Service subclass (e.g. "TranscriptionService"). This works great for read access: MediaFile.last.default_service returns the appropriate object with the expected class:

MediaFile.last.default_service.class.name
# => "TranscriptionService"

However, the association builders will not use the type field for the class, probably due to the :class_name override:

MediaFile.last.create_default_service.class.name
# => "Service"

It seems using a Proc in the class_name option, like you would in a scope, is not supported:

has_one    :default_service, ->(m){where(type: _get_service_type(m))}, :class_name => ->(m){_get_service_type(m)}

results in

NameError: uninitialized constant MediaFile::#<Proc:0x007f9476871588@[...omitted...]/app/models/media_file.rb:102 (lambda)>

One solution is of course to not use create_default_service, as it's easy enough to do yourself. But that seems like inconsistent coding. Is there any other way to use these association builders with the correct STI subclass? I.e. somehow telling rails to generate :class_name dynamically, or to otherwise read the type column in deterring the class?

Andrew Schwartz
  • 4,440
  • 3
  • 25
  • 58

0 Answers0