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

Call build when extend with nested attributes defined

What?
From now on when `accepts_nested_attributes_for` defined and `extend` option
added the overwritten `build` method being called.

[Alireza Bashiri, Martins Polakovs]
This commit is contained in:
Alireza Bashiri 2018-07-27 11:20:45 +04:30
parent 67fa1ad0c3
commit dc16cdd89a
3 changed files with 20 additions and 2 deletions

View file

@ -501,7 +501,7 @@ module ActiveRecord
if attributes["id"].blank? if attributes["id"].blank?
unless reject_new_record?(association_name, attributes) unless reject_new_record?(association_name, attributes)
association.build(attributes.except(*UNASSIGNABLE_KEYS)) association.reader.build(attributes.except(*UNASSIGNABLE_KEYS))
end end
elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes["id"].to_s } elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes["id"].to_s }
unless call_reject_if(association_name, attributes) unless call_reject_if(association_name, attributes)

View file

@ -1094,3 +1094,15 @@ class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveR
assert_equal ["Ship name can't be blank"], part.errors.full_messages assert_equal ["Ship name can't be blank"], part.errors.full_messages
end end
end end
class TestNestedAttributesWithExtend < ActiveRecord::TestCase
setup do
Pirate.accepts_nested_attributes_for :treasures
end
def test_extend_affects_nested_attributes
pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?")
pirate.treasures_attributes = [{ id: nil }]
assert_equal "from extension", pirate.treasures[0].name
end
end

View file

@ -17,7 +17,13 @@ class Pirate < ActiveRecord::Base
after_remove: proc { |p, pa| p.ship_log << "after_removing_proc_parrot_#{pa.id}" } after_remove: proc { |p, pa| p.ship_log << "after_removing_proc_parrot_#{pa.id}" }
has_and_belongs_to_many :autosaved_parrots, class_name: "Parrot", autosave: true has_and_belongs_to_many :autosaved_parrots, class_name: "Parrot", autosave: true
has_many :treasures, as: :looter module PostTreasuresExtension
def build(attributes = {})
super({ name: "from extension" }.merge(attributes))
end
end
has_many :treasures, as: :looter, extend: PostTreasuresExtension
has_many :treasure_estimates, through: :treasures, source: :price_estimates has_many :treasure_estimates, through: :treasures, source: :price_estimates
has_one :ship has_one :ship