Naming Rails has_many: via: polymorphic relationships

I have a problem setting Rails has_many: through: polymorphic relationships.

I know this question is well documented in SO, but I think my problem comes down to my models and foreign_key names as opposed to syntax, i.e. I think this is β€œI have been looking at the code for too long”, which just requires a different set of eyes.

In any case, I have the following setting:

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 

It seems to work fine, without errors, on the part of Milestone. For example, in the terminal, I can write:

 Milestone.first.responsible 

... and get an empty collection, as I expected.

However, on the user side, do:

 User.first.responsibilities 

... returns an AR error:

 ActiveRecord::HasManyThroughAssociationPolymorphicSourceError: Cannot have a has_many :through association 'User#responsibilities' on the polymorphic object 'Responsibility#responsibility'. 

I assume the problem is that I relate to the user's relationship as: responsible. Is it correct?

Any help would be greatly appreciated, thanks.

+8
ruby ruby-on-rails
source share
1 answer

Thanks to @Abid's comment, I thought about the logistics of pulling all responsibilities for the user, which was not feasible. I needed to be more specific in relation to what I wanted from the relationship, and as a result, defining the following working:

 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 expand this by adding additional polymorphic relationships to 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 
+11
source share

All Articles