aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib
diff options
context:
space:
mode:
authorRafael França <rafaelmfranca@gmail.com>2017-08-14 17:43:26 -0400
committerGitHub <noreply@github.com>2017-08-14 17:43:26 -0400
commit8244a45e3ed083b0a9ef239a48095b3ddd81da11 (patch)
tree4b38a2a75a0a56a4dea287582963d8bc36935756 /activerecord/lib
parentefad56a0d93c51d7ebce5007a80df522335430bd (diff)
parentb23e86967c4dfa5aa4f007291458c48dd39b179a (diff)
downloadrails-8244a45e3ed083b0a9ef239a48095b3ddd81da11.tar.gz
rails-8244a45e3ed083b0a9ef239a48095b3ddd81da11.tar.bz2
rails-8244a45e3ed083b0a9ef239a48095b3ddd81da11.zip
Merge pull request #27609 from kamipo/fix_association_primary_key
Fix `reflection.association_primary_key` for `has_many` association
Diffstat (limited to 'activerecord/lib')
-rw-r--r--activerecord/lib/active_record/associations/collection_association.rb11
-rw-r--r--activerecord/lib/active_record/reflection.rb4
2 files changed, 11 insertions, 4 deletions
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
index 38e7ba39d3..ceedf150e3 100644
--- a/activerecord/lib/active_record/associations/collection_association.rb
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -55,13 +55,16 @@ module ActiveRecord
pk_type = reflection.association_primary_key_type
ids = Array(ids).reject(&:blank?)
ids.map! { |i| pk_type.cast(i) }
- records = klass.where(reflection.association_primary_key => ids).index_by do |r|
- r.send(reflection.association_primary_key)
+
+ primary_key = reflection.association_primary_key
+ records = klass.where(primary_key => ids).index_by do |r|
+ r.public_send(primary_key)
end.values_at(*ids).compact
+
if records.size != ids.size
- found_ids = records.map { |record| record.send(reflection.association_primary_key) }
+ found_ids = records.map { |record| record.public_send(primary_key) }
not_found_ids = ids - found_ids
- klass.all.raise_record_not_found_exception!(ids, records.size, ids.size, reflection.association_primary_key, not_found_ids)
+ klass.all.raise_record_not_found_exception!(ids, records.size, ids.size, primary_key, not_found_ids)
else
replace(records)
end
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index 7f1601805c..564dbcb342 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -715,6 +715,10 @@ module ActiveRecord
Associations::HasManyAssociation
end
end
+
+ def association_primary_key(klass = nil)
+ primary_key(klass || self.klass)
+ end
end
class HasOneReflection < AssociationReflection # :nodoc: