-
-
Save RafeHatfield/6588252 to your computer and use it in GitHub Desktop.
Reverse Polymorphic Associations An email digest can contain either articles or questions, called as @email_digest.digest_elements
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
class EmailDigest < ActiveRecord::Base | |
has_many :digest_elements | |
has_many :articles, :through => :digest_elements, :source => :element, :source_type => 'Article' | |
has_many :questions, :through => :digest_elements, :source => :element, :source_type => 'Question' | |
end | |
class Article < ActiveRecord::Base | |
has_one :article_element, :as =>:element | |
has_one :email_digest, :through => :digest_elements | |
end | |
class Question < ActiveRecord::Base | |
has_one :article_element, :as =>:element | |
has_one :email_digest, :through => :digest_elements | |
end | |
class DigestElement < ActiveRecord::Base | |
belongs_to :email_digest | |
belongs_to :element, :polymorphic => true | |
end | |
d = EmailDigest.new | |
d.digest_elements # [] | |
a = Article.new | |
d.save | |
d.digest_elements.create(:element => a) | |
d.digest_elements | |
d.articles |
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
class CreateDigestElements < ActiveRecord::Migration | |
def change | |
create_table :digest_elements do |t| | |
t.integer :email_digest_id | |
t.integer :element_id | |
t.string :element_type | |
t.timestamps | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment