Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use _read_attribute when autosaving has_one associations #48489

Merged
merged 1 commit into from
Jun 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/autosave_association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ def save_has_one_association(reflection)
if autosave && record.marked_for_destruction?
record.destroy
elsif autosave != false
key = reflection.options[:primary_key] ? public_send(reflection.options[:primary_key]) : id
key = reflection.options[:primary_key] ? _read_attribute(reflection.options[:primary_key].to_s) : id

if (autosave && record.changed_for_autosave?) || _record_changed?(reflection, record, key)
unless reflection.through_reflection
Expand Down
7 changes: 7 additions & 0 deletions activerecord/test/cases/autosave_association_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -798,6 +798,13 @@ def test_assign_ids_with_cpk_for_two_models
assert_includes order.books, cpk_books(:cpk_great_author_second_book)
end

def test_has_one_cpk_has_one_autosave_with_id
book = Cpk::Book.create!(author_id: 1, number: 3, shop_id: 2)
order = Cpk::OrderWithPrimaryKeyAssociatedBook.create!(book: book, shop_id: 2)

assert_equal(book.order.id, order.id)
end

def test_assign_ids_for_through_a_belongs_to
firm = Firm.new("name" => "Apple")
firm.developer_ids = [developers(:david).id, developers(:jamis).id]
Expand Down
4 changes: 4 additions & 0 deletions activerecord/test/models/cpk/order.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,8 @@ class BrokenOrder < Order
has_many :books
has_one :book
end

class OrderWithPrimaryKeyAssociatedBook < Order
has_one :book, primary_key: :id, foreign_key: :order_id
end
end