Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #7143 (closed enhancement: fixed)

Opened 2 years ago

Last modified 2 years ago

[PATCH] allow polymorphic :source for has_many :through

Reported by: protocool Assigned to: core
Priority: normal Milestone: 1.x
Component: ActiveRecord Version:
Severity: normal Keywords: polymorphic has_many :through
Cc: carlivar

Description

This patch adds tests, documentation and code to support polymorphic belongs_to associations as the source in a has_many :through.

class Post < ActiveRecord::Base
  has_many :taggings, :as => :taggable
end

class Tagging < ActiveRecord::Base
  belongs_to :tag
  belongs_to :taggable, :polymorphic => true
end

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :tagged_posts, :through => :taggings, :source => :taggable, :source_type => 'Post'
end

Tag.find(:first).tagged_posts # returns a list of posts associated with this tag
Tag.find(:first, :include => :tagged_posts) # same, but eager loaded
Tag.find(:first).tagged_posts << Post.find(:first) # correctly sets taggable_id and taggable_type 

It also supports fully-bidirectional polymorphic joins - where the join table looks like:

class Ownerships < ActiveRecord::Base
  belongs_to :owner, :polymorphic => true
  belongs_to :owned, :polymorphic => true
end

Attachments

golden.diff (14.8 kB) - added by protocool on 01/17/07 22:47:51.

Change History

01/17/07 22:47:51 changed by protocool

  • attachment golden.diff added.

(in reply to: ↑ description ) 02/20/07 21:11:07 changed by carlivar

There seems to be a big need for this, given workarounds like this:

http://blog.hasmanythrough.com/2006/04/03/polymorphic-through

Hopefully this patch will get some attention soon?

02/20/07 21:11:17 changed by carlivar

  • cc set to carlivar.

03/13/07 05:24:58 changed by technoweenie

  • status changed from new to closed.
  • resolution set to fixed.

From the "why the hell didn't trac close it" department.... fixed in [6408]

Thanks for the patch protocool!