Skip to content

Commit

Permalink
fix after_initialize edge case (close rails#2074 and close rails#2175)
Browse files Browse the repository at this point in the history
fix behavior when after_initialize is defined and a block is passed to Base.create
  • Loading branch information
hmcfletch authored and cldwalker committed Jul 24, 2011
1 parent d33eb07 commit f956759
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 2 deletions.
3 changes: 1 addition & 2 deletions activerecord/lib/active_record/base.rb
Expand Up @@ -504,8 +504,7 @@ def create(attributes = nil, options = {}, &block)
if attributes.is_a?(Array)
attributes.collect { |attr| create(attr, options, &block) }
else
object = new(attributes, options)
yield(object) if block_given?
object = new(attributes, options, &block)
object.save
object
end
Expand Down
23 changes: 23 additions & 0 deletions activerecord/test/cases/base_test.rb
Expand Up @@ -21,6 +21,7 @@
require 'models/person'
require 'models/edge'
require 'models/joke'
require 'models/wholesale_product'
require 'rexml/document'
require 'active_support/core_ext/exception'

Expand Down Expand Up @@ -260,6 +261,28 @@ def test_initialize_with_invalid_attribute
end
end

def test_create_with_after_initialize
wp1 = WholesaleProduct.create(:msrp => 10)
assert_equal(10, wp1.msrp)
assert_equal(5, wp1.wholesale)

wp2 = WholesaleProduct.create(:wholesale => 10)
assert_equal(20, wp2.msrp)
assert_equal(10, wp2.wholesale)

wp3 = WholesaleProduct.create do |wp|
wp.msrp = 10
end
assert_equal(10, wp3.msrp)
assert_equal(5, wp3.wholesale)

wp4 = WholesaleProduct.create do |wp|
wp.wholesale = 10
end
assert_equal(20, wp4.msrp)
assert_equal(10, wp4.wholesale)
end

def test_load
topics = Topic.find(:all, :order => 'id')
assert_equal(4, topics.size)
Expand Down
13 changes: 13 additions & 0 deletions activerecord/test/models/wholesale_product.rb
@@ -0,0 +1,13 @@
class WholesaleProduct < ActiveRecord::Base

after_initialize :set_prices

def set_prices
if msrp.nil? && !wholesale.nil?
self.msrp = 2 * wholesale
elsif !msrp.nil? && wholesale.nil?
self.wholesale = msrp / 2
end
end

end
5 changes: 5 additions & 0 deletions activerecord/test/schema/schema.rb
Expand Up @@ -678,6 +678,11 @@ def create_table(*args, &block)
t.references :wheelable, :polymorphic => true
end

create_table :wholesale_products, :force => true do |t|
t.integer :msrp
t.integer :wholesale
end

create_table :zines, :force => true do |t|
t.string :title
end
Expand Down

0 comments on commit f956759

Please sign in to comment.