Add create_association! for belongs_to

This commit is contained in:
Jon Leighton 2011-01-16 18:25:50 +00:00 committed by Aaron Patterson
parent 8f88a28416
commit 52c47556b7
5 changed files with 26 additions and 3 deletions

@ -1533,10 +1533,10 @@ def collection_accessor_methods(reflection, writer = true)
def association_constructor_methods(reflection)
constructors = {
"build_#{reflection.name}" => "build",
"create_#{reflection.name}" => "create"
"build_#{reflection.name}" => "build",
"create_#{reflection.name}" => "create",
"create_#{reflection.name}!" => "create!"
}
constructors["create_#{reflection.name}!"] = "create!" if reflection.macro == :has_one
constructors.each do |name, proxy_name|
redefine_method(name) do |*params|

@ -6,6 +6,10 @@ def create(attributes = {})
replace(@reflection.create_association(attributes))
end
def create!(attributes = {})
build(attributes).tap { |record| record.save! }
end
def build(attributes = {})
replace(@reflection.build_association(attributes))
end

@ -120,6 +120,23 @@ def test_building_the_belonging_object_with_primary_key
assert_equal apple.name, client.firm_name
end
def test_create!
client = Client.create!(:name => "Jimmy")
account = client.create_account!(:credit_limit => 10)
assert_equal account, client.account
assert account.persisted?
client.save
client.reload
assert_equal account, client.account
end
def test_failing_create!
client = Client.create!(:name => "Jimmy")
assert_raise(ActiveRecord::RecordInvalid) { client.create_account! }
assert_not_nil client.account
assert client.account.new_record?
end
def test_natural_assignment_to_nil
client = Client.find(3)
client.firm = nil

@ -124,6 +124,7 @@ class Client < Company
belongs_to :firm_with_primary_key_symbols, :class_name => "Firm", :primary_key => :name, :foreign_key => :firm_name
belongs_to :readonly_firm, :class_name => "Firm", :foreign_key => "firm_id", :readonly => true
has_many :accounts, :through => :firm
belongs_to :account
# Record destruction so we can test whether firm.clients.clear has
# is calling client.destroy, deleting from the database, or setting

@ -154,6 +154,7 @@ def create_table(*args, &block)
t.string :name
t.integer :client_of
t.integer :rating, :default => 1
t.integer :account_id
end
add_index :companies, [:firm_id, :type, :rating, :ruby_type], :name => "company_index"