All threads / Polymorphic association via concern giving undefined method relation_delegate_class

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Polymorphic association via concern giving undefined method relation_delegate_class

Tom Iwaniec asked in Rails

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!

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 34,674+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.