views:

18

answers:

0

This one catches me out a lot.

class Repository < ActiveRecord::Base
  has_one :database, :storage
  before_create :provision_database, :provision_storage

  def provision_database
    self.database = Database.new # works
  end
  def provision_storage
    storage = Storage.new # doesn't work
  end
end

class Database < ActiveRecord::Base
  belongs_to :repository
end

class Storage < ActiveRecord::Base
  belongs_to :repository
end

repo = Repository.new
repo.run_callbacks(:before_create)

assert !repo.database.nil? # passes
assert !repo.storage.nil? # fails

Why is it that referring to an attribute without self (in provision_storage) doesn't work where as it does if you prefix it with self (in provision_database)?