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

Ensure that association_ids uses the correct attribute where the association is a has_many :through with a :primary_key option on the source reflection. [#6376 state:resolved]

This commit is contained in:
Jon Leighton 2011-02-14 20:39:51 +00:00
parent b131cfba05
commit f0b9805029
4 changed files with 20 additions and 2 deletions

View file

@ -1582,9 +1582,12 @@ module ActiveRecord
redefine_method("#{reflection.name.to_s.singularize}_ids") do
if send(reflection.name).loaded? || reflection.options[:finder_sql]
send(reflection.name).map { |r| r.id }
records = send(reflection.name)
records.map { |r| r.send(reflection.association_primary_key) }
else
send(reflection.name).select("#{reflection.quoted_table_name}.#{reflection.klass.primary_key}").except(:includes).map! { |r| r.id }
column = "#{reflection.quoted_table_name}.#{reflection.association_primary_key}"
records = send(reflection.name).select(column).except(:includes)
records.map! { |r| r.send(reflection.association_primary_key) }
end
end
end

View file

@ -394,6 +394,10 @@ module ActiveRecord
@source_reflection_names ||= (options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }
end
def association_primary_key
source_reflection.association_primary_key
end
def check_validity!
if through_reflection.nil?
raise HasManyThroughAssociationNotFoundError.new(active_record.name, self)

View file

@ -718,4 +718,14 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
assert_equal post.tags, post.interpolated_tags
assert_equal post.tags, post.interpolated_tags_2
end
def test_primary_key_option_on_source
post = posts(:welcome)
category = categories(:general)
categorization = Categorization.create!(:post_id => post.id, :named_category_name => category.name)
assert_equal [category], post.named_categories
assert_equal [category.name], post.named_category_ids # checks when target loaded
assert_equal [category.name], post.reload.named_category_ids # checks when target no loaded
end
end

View file

@ -90,6 +90,7 @@ class Post < ActiveRecord::Base
has_many :standard_categorizations, :class_name => 'Categorization', :foreign_key => :post_id
has_many :author_using_custom_pk, :through => :standard_categorizations
has_many :authors_using_custom_pk, :through => :standard_categorizations
has_many :named_categories, :through => :standard_categorizations
has_many :readers
has_many :readers_with_person, :include => :person, :class_name => "Reader"