Search code examples
ruby-on-railsactiverecordmodel-associations

How to define runtime source_type inside "has many through" polymorphic association?


Is there any way to define source_type runtime inside rails has_many through polymorphic association.

Below code should give you brief idea .. but its not working.. any suggestions ??

class A < ...
  has_many :message_messagables, :foreign_key => :message_id

  has_many :messagables, :through => :message_messagables, :source => :messagable, :source_type => lambda { |a| a.custom_type }

 def custom_type
   raise "needs to be defined inside subclass"
 end

end


class MessageMessagable < ... 
 belongs_to :messagable, :polymorphic => true #[C, D]
 belongs_to :message
end

class B < A

 def custom_type
   "C"
 end
end

class E < A
 def custom_type
   "D"
 end

end

Solution

  • I met the same problem. I resolved it by listing all avaiable source types and added a dispatch method.

    class A < ...
      has_many :message_messagables, :foreign_key => :message_id
    
      # list all source types as association
      %w(email file).each do |source_type|
        has_many source_type.pluralize.to_sym, :through => :message_messagables, :source => :messagable, :source_type => source_type
      end
    
      # dispatch methodk
      def messagables
        public_send custom_type.pluralize.to_sym
      end
    end