提交 f956759f 编写于 作者: L Les Fletcher 提交者: Gabriel Horner

fix after_initialize edge case (close #2074 and close #2175)

fix behavior when after_initialize is defined and a block is passed to Base.create
上级 d33eb075
......@@ -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
......
......@@ -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'
......@@ -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)
......
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
\ No newline at end of file
......@@ -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
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册