Skip to content

Instantly share code, notes, and snippets.

@clowder
Forked from mudge/gist:263139
Created December 9, 2011 14:04
Show Gist options
  • Save clowder/1451644 to your computer and use it in GitHub Desktop.
Save clowder/1451644 to your computer and use it in GitHub Desktop.
Polymorphic has_many :through in Rails 2.3
# A polymorphic has_many :through relationship in Rails 2.3
# based on Josh Susser's "The other side of polymorphic :through associations"
# http://blog.hasmanythrough.com/2006/4/3/polymorphic-through
class Authorship < ActiveRecord::Base
belongs_to :author
belongs_to :publication, :polymorphic => true
end
class Author < ActiveRecord::Base
has_many :authorships
with_options :through => :authorships, :source => :publication do |author|
author.has_many :books, :source_type => 'Book'
author.has_many :articles, :source_type => 'Article'
end
def publications
articles + books
end
end
class Article < ActiveRecord::Base
has_many :authorships, :as => :publication
has_many :authors, :through => :authorships
end
class Book < ActiveRecord::Base
has_many :authorships, :as => :publication
has_many :authors, :through => :authorships
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment