Permalink
Browse files

belongs_to records should be initialized within the association scope

  • Loading branch information...
1 parent 3ef6937 commit bf24fe810c0591619ac01cc88d8a40423895d9d7 @jonleighton jonleighton committed with tenderlove Jan 16, 2011
View
10 activerecord/lib/active_record/associations/belongs_to_association.rb
@@ -3,15 +3,15 @@ module ActiveRecord
module Associations
class BelongsToAssociation < AssociationProxy #:nodoc:
def create(attributes = {})
- replace(@reflection.create_association(attributes))
+ new_record(:create_association, attributes)
end
def create!(attributes = {})
build(attributes).tap { |record| record.save! }
end
def build(attributes = {})
- replace(@reflection.build_association(attributes))
+ new_record(:build_association, attributes)
end
def replace(record)
@@ -34,6 +34,12 @@ def updated?
end
private
+ def new_record(method, attributes)
+ record = scoped.scoping { @reflection.send(method, attributes) }
+ replace(record)
+ record
+ end
+
def update_counters(record)
counter_cache_name = @reflection.counter_cache_column
View
21 activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -608,4 +608,25 @@ def test_polymorphic_with_custom_foreign_type
assert_equal groucho, sponsor.sponsorable
assert_equal groucho, sponsor.thing
end
+
+ def test_build_with_conditions
+ client = companies(:second_client)
+ firm = client.build_bob_firm
+
+ assert_equal "Bob", firm.name
+ end
+
+ def test_create_with_conditions
+ client = companies(:second_client)
+ firm = client.create_bob_firm
+
+ assert_equal "Bob", firm.name
+ end
+
+ def test_create_bang_with_conditions
+ client = companies(:second_client)
+ firm = client.create_bob_firm!
+
+ assert_equal "Bob", firm.name
+ end
end
View
1 activerecord/test/models/company.rb
@@ -123,6 +123,7 @@ class Client < Company
belongs_to :firm_with_primary_key, :class_name => "Firm", :primary_key => "name", :foreign_key => "firm_name"
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
+ belongs_to :bob_firm, :class_name => "Firm", :foreign_key => "client_of", :conditions => { :name => "Bob" }
has_many :accounts, :through => :firm
belongs_to :account

0 comments on commit bf24fe8

Please sign in to comment.