Skip to content

Instantly share code, notes, and snippets.

@erithmetic
Created March 29, 2013 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erithmetic/5271064 to your computer and use it in GitHub Desktop.
Save erithmetic/5271064 to your computer and use it in GitHub Desktop.
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