Created
March 29, 2013 14:04
-
-
Save erithmetic/5271064 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Article < ActiveRecord::Base | |
has_many :authorships | |
has_many :authors, through: :authorships | |
def total_kudos | |
authors.sum(&:kudos) | |
end | |
end | |
# OK | |
author1 = Author.new kudos: 1 | |
author2 = Author.new kudos: 2 | |
a = Article.new | |
a.authors << author1 | |
a.authors << author2 | |
a.total_kudos.should == 3 | |
# FAILS | |
author1 = Author.new kudos: 1 | |
author2 = Author.new kudos: 2 | |
a = Article.new | |
a.authorships.build author: author1 | |
a.authorships.build author: author2 | |
a.total_kudos.should == 3 | |
# AR does not populate the #authors association when authorships are built |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment