bschaeffer
bschaeffer

Reputation: 2904

Rails: Single Record, Many Polymorphic

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.

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

Answers (1)

Shailesh S Patil
Shailesh S Patil

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

Related Questions