Naming a Rails has_many :through :polymorphic relationship

ruby, ruby-on-rails, ruby-on-rails-3.2

Solution

Thanks to @Abid's comment i got thinking about the logistics of pulling in all `responsibilities` for a user, which wasn't going to be feasible. I needed to be more specific about what i wanted from the relationship and as result defining the following worked:

class User < ActiveRecord::Base
  has_many :responsible_items, :foreign_key => :responsible_id
  has_many :milestone_responsibilities, :through => :responsible_items, :source => :responsibility, :source_type => 'Milestone'
end

I can then extend this as i add further polymorphic relationships on other models for example:

class User < ActiveRecord::Base
  has_many :responsible_items, :foreign_key => :responsible_id
  has_many :milestone_responsibilities, :through => :responsible_items, :source => :responsibility, :source_type => 'Milestone'
  has_many :task_responsibilities, :through => :responsible_items, :source => :responsibility, :source_type => 'Task'
end

Problem

Im having a bit of an issue setting up a Rails has_many :through :polymorphic relationship. I'm aware this subject is well documented on SO but i think my problem is down to my model and foreign_key names as opposed to syntax i.e i think this is a "i've been looking at code too long" issue that just requires another set of eyes. Anyway i have the following setup: ``` class Milestone < ActiveRecord::Base has_many :responsible_items, :as => :responsibility has_many :responsible, :through => :responsible_items end class ResponsibleItem < ActiveRecord::Base belongs_to :responsible, :class_name => "User" belongs_to :responsibility, :polymorphic => true end class User < ActiveRecord::Base has_many :responsible_items, :foreign_key => :responsible_id has_many :responsibilities, :through => :responsible_items end ``` This seems to work fine, without error, from the Milestone side of things. For example in terminal i can write: ``` Milestone.first.responsible ``` …and get an empty collection as i'd expect. However, from the User side of things, running: ``` User.first.responsibilities ``` …is returning an AR error: ``` ActiveRecord::HasManyThroughAssociationPolymorphicSourceError: Cannot have a has_many :through association 'User#responsibilities' on the polymorphic object 'Responsibility#responsibility'. ``` I'm assuming the issue is something to do with the fact that i am referring to the User relationship as :responsible. Is this right? Any help would be much appreciated, thanks.

Original source

Related problems