Skip to content

Commit 9c9fb19

Browse files
himesh-rarthurnn
authored andcommitted
Changed id-writer to save join table records based on association primary key rails#20995
Changed id-writer to save join table records based on association primary key
1 parent 0e189cb commit 9c9fb19

File tree

2 files changed

+5
-2
lines changed

2 files changed

+5
-2
lines changed

activerecord/lib/active_record/associations/collection_association.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,10 @@ def ids_writer(ids)
7272
pk_type = reflection.primary_key_type
7373
ids = Array(ids).reject(&:blank?)
7474
ids.map! { |i| pk_type.cast(i) }
75-
replace(klass.find(ids).index_by(&:id).values_at(*ids))
75+
records = klass.where(reflection.association_primary_key => ids).index_by do |r|
76+
r.send(reflection.association_primary_key)
77+
end.values_at(*ids)
78+
replace(records)
7679
end
7780

7881
def reset

activerecord/test/cases/associations/has_many_through_associations_test.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -882,7 +882,7 @@ def test_collection_singular_ids_setter_with_string_primary_keys
882882
def test_collection_singular_ids_setter_raises_exception_when_invalid_ids_set
883883
company = companies(:rails_core)
884884
ids = [Developer.first.id, -9999]
885-
assert_raises(ActiveRecord::RecordNotFound) {company.developer_ids= ids}
885+
assert_raises(ActiveRecord::AssociationTypeMismatch) {company.developer_ids= ids}
886886
end
887887

888888
def test_build_a_model_from_hm_through_association_with_where_clause

0 commit comments

Comments
 (0)