Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add create_association! for belongs_to

  • Loading branch information...
commit 52c47556b7cf55549f97f3cfd5f69b2563198eac 1 parent 8f88a28
@jonleighton jonleighton authored tenderlove committed
View
6 activerecord/lib/active_record/associations.rb
@@ -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|
View
4 activerecord/lib/active_record/associations/belongs_to_association.rb
@@ -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
View
17 activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -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
View
1  activerecord/test/models/company.rb
@@ -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
1  activerecord/test/schema/schema.rb
@@ -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"
Please sign in to comment.
Something went wrong with that request. Please try again.