Skip to content

Commit

Permalink
Create through associations can now work with blocks.
Browse files Browse the repository at this point in the history
Signed-off-by: Michael Koziarski <michael@koziarski.com>

[#248 state:resolved]
  • Loading branch information
ryanb authored and NZKoz committed May 24, 2008
1 parent b88ceb7 commit 6cba97d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -166,12 +166,18 @@ def create(attrs = {})
if attrs.is_a?(Array)
attrs.collect { |attr| create(attr) }
else
create_record(attrs) { |record| record.save }
create_record(attrs) do |record|
yield(record) if block_given?
record.save
end
end
end

def create!(attrs = {})
create_record(attrs) { |record| record.save! }
create_record(attrs) do |record|
yield(record) if block_given?
record.save!
end
end

# Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and
Expand Down
15 changes: 9 additions & 6 deletions activerecord/test/cases/associations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -161,12 +161,15 @@ def test_save_on_parent_saves_children
end

def test_create_via_association_with_block
post1 = Post.create(:title => "setting body with a block") {|p| p.body = "will work"}
assert_equal post1.body, "will work"
assert_nothing_raised do
post2 = authors(:david).posts.create(:title => "setting body with a block") {|p| p.body = "won't work"}
end
assert_equal post2.body, "won't work"
post = authors(:david).posts.create(:title => "New on Edge") {|p| p.body = "More cool stuff!"}
assert_equal post.title, "New on Edge"
assert_equal post.body, "More cool stuff!"
end

def test_create_with_bang_via_association_with_block
post = authors(:david).posts.create!(:title => "New on Edge") {|p| p.body = "More cool stuff!"}
assert_equal post.title, "New on Edge"
assert_equal post.body, "More cool stuff!"
end

def test_failed_reload_returns_nil
Expand Down

0 comments on commit 6cba97d

Please sign in to comment.