MissingAttributeError from within after_initialize

I found this interesting. If you use an after_initialize hook in an ActiveRecord model for some reason and you hit upon one of the attribute accessor methods, the following exception may reveal itself.

ActiveRecord::MissingAttributeError: missing attribute:

Specifically, I came across it when referencing the has_many side of an association from within a belongs_to model. For example:

class Person < ActiveRecord::Base
  belongs_to :person_group
 
  def after_initialize
    # Unsafe
    logger.info self.attribute.inspect
    # Safe to use
    logger.info self.attributes['attribute'].inspect
  end
end
 
class PersonGroup < ActiveRecord::Base
  has_many :people
 
  before_destroy :cb
 
  private
 
  def cb
    unless people_ids.blank?  # Rails exception
      Person.update_all ...
    end
  end
end

2 Comments

  1. jack pie
    Posted 10/14/2009 at 1:34 pm | Permalink

    https://rails.lighthouseapp.com/projects/8994/tickets/3165-activerecordmissingattributeerror-after-update-to-rails-v-234

    is the rails bug for this issue. You’re not alone ;)

  2. Posted 3/3/2010 at 3:32 pm | Permalink

    Just got bit by this problem, thanks for writing it up so I could find it while searching!

Post a Comment

You must be logged in to post a comment.