Reputation: 2904
I'm sure there is a better title for this, so sorry about that.
I've got a Verification
model. Ideally, there would various other model types that are able to associate themselves with the a single Verification
record. For instance.
Verification(id: 1, verifiable_type: 'Reference')
Reference(id: 1, verification_id: 1)
Reference(id: 2, verification_id: 1)
Verification(id: 2, verifiable_type: 'Degree')
Degree(id: 1, verification_id: 2)
Degree(id: 2, verification_id: 2)
I was hoping for something as simple as a dynamic :class_name
option on the the has_many
:
class Verification < ActiveRecord::Base
has_many :verifiables, class_name: -> { dynamic_class_name }
end
I am 99% sure that the reverse associations would actually work out of the box. So, using the records from above, the following should be no problem:
class Reference < ActiveRecord::Base
belongs_to :verification
end
class Degree < ActiveRecord::Base
belongs_to :verification
end
Any suggestions?
Upvotes: 0
Views: 48
Reputation: 26
Instead of
has_many :verifiables, class_name: -> { dynamic_class_name }
replace it with
def self.varifiables(type)
where(verifiable_type: type)
end
Upvotes: 1