Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4030216
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T11:26:36+00:00 2026-05-20T11:26:36+00:00

I am trying to set some default values for an object using after_initialize .

  • 0

I am trying to set some default values for an object using after_initialize. The problem I am having is that I would like this to be called no matter how the object is created.

My class:

class Foo < ActiveRecord::Base

  serialize :data

  after_initialize :init

  def init
    self.data ||= {}
    self.bar ||= "bar"
    self.baz ||= "baz"
  end

end

Everything works fine if I call Foo.new, Foo.new(:bar => "things") and Foo.create(:baz => 'stuff'). However when I use a block with create the after_initialize callback doesn’t get run.

obj = Foo.create do |f|
  f.bar = "words"
  f.data = { :attr_1 => 1, :attr_2 => 2 }
end

This just yields obj.baz => nil instead of "baz" with the other attributes set correctly.

Am I missing something with the way callbacks are executed, with the differences with calling create with a block and without or are default values getting clobbered by the block?

UPDATE

Found the issue.

It turns out that calling create with block and without are subtly different. When you call create without a block and just pass in a hash of parameters, for all intents and purposes you are calling Foo.new({<hash of argument>}).save, and the after_initialize callback gets executed right before the save like you would expect.

When you call create with a block something a little different happens. The order of events is Foo.new is called with whatever arguments you pass in, then after_initialize gets called, then the block gets run. So if you are using the block (as I was) interchangeably with the hash parameters just to make things a little bit more readable you could get bit because your after_initialize is run before all of the parameters you intend to set are actually set.

I got bit because I was doing some extra work in the after_initialize setting some extra required attributes based on the value of what was getting passed. Since nothing was actually set when after_initialize got called, nothing got set correctly and my validations failed.

I ended up having to make to calls to init. Once on after_initialize and once on before_validation. Not the cleanest, but it solved the issue.

Thanks go to Brandon for pointing me in the right direction.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T11:26:37+00:00Added an answer on May 20, 2026 at 11:26 am

    I’m unable to reproduce this. I happen to have an application handy with the following (simplified) class:

    class Service < ActiveRecord::Base
      serialize        :data, Hash
      after_initialize :create_default_data
      attr_accessible  :data, :token
    
      protected
    
        def create_default_data
          self.data ||= Hash.new
        end
    end
    

    Here’s an IRB session:

    ruby-1.9.2-p136 :001 > obj = Service.create do |s|
    ruby-1.9.2-p136 :002 >     s.token = "abc"
    ruby-1.9.2-p136 :003?>   end
     => #<Service id: 22, user_id: nil, type: nil, data: {}, created_at: "2011-03-05 04:18:00", updated_at: "2011-03-05 04:18:00", token: "abc"> 
    ruby-1.9.2-p136 :004 > obj.data
     => {}
    

    As you can see, data as initialized in the after_initialize method to an empty hash. The Rails code indicates this makes sense as well; in create:

    def create(attributes = nil, &block)
      if attributes.is_a?(Array)
        attributes.collect { |attr| create(attr, &block) }
      else
        object = new(attributes)
        yield(object) if block_given?
        object.save
        object
      end
    end
    

    So create calls new and assigns the value to object before it yields. Here’s the relevant part in new:

    def initialize(attributes = nil)
      # truncated for space
      result = yield self if block_given?
      run_callbacks :initialize
      result
    end
    

    As you can see, new unconditionally calls the initialize callbacks before it returns, and thus before create even yields to the block you pass. By the time your block gets the object, the after_initialize method has already executed.

    Double check that (1) your version of Rails is up to date (3.0.5 as of now I believe) and that (2) nothing is setting baz without you realizing it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to write a shell script that, when run, will set some environment
i'm trying to set up the selenium-maven-plugin and having some difficulties i hope somebody
I'm having some minor problems with some animations I'm trying to set up. I
I'm trying to set up a Rails Template that would allow for comprehensive set-up
I am using asp.net mvc 2.0(default binding model) and I have this problem. I
I'm playing around with Rhino Mocks and am trying to set some dummy results
I'm trying to set up AutoHotkey macros for some common tasks, and I want
I'm trying to automate some stuff in MS Excel. When I try to set
Where would set_include_path(../../); point to? I am trying to run some PHP code on
I am trying set up databinding as described in the title. The problem I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.