mirror of
https://github.com/github/rails.git
synced 2026-01-10 07:07:54 -05:00
Merge pull request #12375 from arthurnn/inverse_after_find_or_initialize
Inverse after find or initialize
This commit is contained in:
@@ -1,5 +1,10 @@
|
||||
## unreleased ##
|
||||
|
||||
* When calling the method .find_or_initialize_by_* from a collection_proxy
|
||||
it should set the inverse_of relation even when the entry was found on the db.
|
||||
|
||||
*arthurnn*
|
||||
|
||||
* Callbacks on has_many should access the in memory parent if a inverse_of is set.
|
||||
|
||||
*arthurnn*
|
||||
|
||||
@@ -77,10 +77,12 @@ module ActiveRecord
|
||||
def method_missing(method, *args, &block)
|
||||
match = DynamicFinderMatch.match(method)
|
||||
if match && match.instantiator?
|
||||
send(:find_or_instantiator_by_attributes, match, match.attribute_names, *args) do |r|
|
||||
proxy_association.send :set_owner_attributes, r
|
||||
proxy_association.send :add_to_target, r
|
||||
yield(r) if block_given?
|
||||
send(:find_or_instantiator_by_attributes, match, match.attribute_names, *args) do |record|
|
||||
proxy_association.send :set_owner_attributes, record
|
||||
proxy_association.send :add_to_target, record
|
||||
yield(record) if block_given?
|
||||
end.tap do |record|
|
||||
proxy_association.send :set_inverse_instance, record
|
||||
end
|
||||
|
||||
elsif target.respond_to?(method) || (!proxy_association.klass.respond_to?(method) && Class.respond_to?(method))
|
||||
|
||||
@@ -662,6 +662,17 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
|
||||
end
|
||||
end
|
||||
|
||||
def test_inverse_after_find_or_initialize
|
||||
firm = companies(:first_firm)
|
||||
client = firm.clients_of_firm.find_or_initialize_by_client_of(firm.id)
|
||||
assert_no_queries do
|
||||
assert_equal firm, client.firm
|
||||
end
|
||||
|
||||
firm.name = "A new firm"
|
||||
assert_equal firm.name, client.firm.name
|
||||
end
|
||||
|
||||
def test_new_aliased_to_build
|
||||
company = companies(:first_firm)
|
||||
new_client = assert_no_queries { company.clients_of_firm.new("name" => "Another Client") }
|
||||
|
||||
Reference in New Issue
Block a user