Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
create with a block and after_initialize have inconsistant behavior #2074
The problem I am running into when I create and object that uses after_initialize to set up default values for attributes that are dependent on other attributes and set some of the values for the new object in a block.
Let's say I have the following class with an after_initialize to set up the msrp based on the given wholesale value.
class Product < ActiveRecord::Base after_initialize :set_defaults def set_defaults self.msrp = 2 * wholesale unless wholesale.nil? end end
If I create a product like so
Product.create(:name => 'Awesome Product', :wholesale => 10)
I'll get the following product object:
<Product id:1234, name: "Awesome Product", wholesale: 10, msrp: 20>
But if I create the object like so
Product.create do |p| p.name = 'Awesome Product' p.wholesale => 10 end
I''l get the following
<Product id:1234, name: "Awesome Product", wholesale: 10, msrp: nil>
I know why this happens. It happens because create (in ActiveRecord::Base) with a block given calls new first, which triggers after_initialize, then yields to the block with the new object. Since the wholesale value is set in the block, after_initialize doesn't have access to it to set msrp.
Sorry for not providing a patch, I haven't dug around enough to figure out what would be the best way to adress this. Figured it was important enough to at least raise the issue first.