-
-
Save tors/575235 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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