1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

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

View file

@ -1534,9 +1534,9 @@ module ActiveRecord
def association_constructor_methods(reflection)
constructors = {
"build_#{reflection.name}" => "build",
"create_#{reflection.name}" => "create"
"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|

View file

@ -6,6 +6,10 @@ module ActiveRecord
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

View file

@ -120,6 +120,23 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
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

View file

@ -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

View file

@ -154,6 +154,7 @@ ActiveRecord::Schema.define do
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"