Polymorphic association via concern giving undefined method relation_delegate_class
Not sure if the forum is a good place to ask technical questions like this, but I have a heartable concern that I will be applying to several models:
module Heartable
extend ActiveSupport::Concern
included do
has_many :hearts, as: :heartable, dependent: :destroy
has_many :hearters, through: :hearts, source: "user"
...
end
end
Heart.rb:
class Heart < ApplicationRecord
belongs_to :user
belongs_to :heartable, polymorphic: true
validates :user, uniqueness: { scope: [:heartable_id ,:heartable_type],
message: "You've already loved this!" }
end
Listing.rb (one of the heartable types):
class Listing < ApplicationRecord
include Heartable
end
And finally in User.rb:
has_many :hearts, dependent: :destroy
has_many :heartables, through: :hearts, source_type: "Heartable" #this is the problematic line
Everything works in the association (User.hearts, Heartable.hearts, Heartable.hearters) except for User.heartables, which returns:
NoMethodError: undefined method `relation_delegate_class' for Heartable:Module
If I change the association in User.rb to:
has_many :heartables, through: :hearts, source: "heartable"
User.heartables returns:
ActiveRecord::HasManyThroughAssociationPolymorphicSourceError: Cannot have a has_many :through association 'User#heartables' on the polymorphic object 'Heartable#heartable' without 'source_type'. Try adding 'source_type: "Heartable"' to 'has_many :through' definition.
If I change the association in User.rb to:
has_many :heartables, through: :hearts, source_type: "Listing"
Then it will work, but defeats the purpose of having the association on a concern so that I can easily apply it to other models.
Thanks for your time!