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

Merge pull request #3748 from samsonasu/has_many_custom_pk_new_record

New records should load has_many relationships with custom primary keys
This commit is contained in:
Jon Leighton 2011-11-27 13:05:19 -08:00
commit b00cf122e2
3 changed files with 33 additions and 2 deletions

View file

@ -235,7 +235,7 @@ module ActiveRecord
# This method is abstract in the sense that it relies on
# +count_records+, which is a method descendants have to provide.
def size
if owner.new_record? || (loaded? && !options[:uniq])
if !find_target? || (loaded? && !options[:uniq])
target.size
elsif !loaded? && options[:group]
load_target.size

View file

@ -103,6 +103,10 @@ module ActiveRecord
end
end
end
def foreign_key_present?
owner.attribute_present?(reflection.association_primary_key)
end
end
end
end

View file

@ -8,6 +8,7 @@ require 'models/reply'
require 'models/category'
require 'models/post'
require 'models/author'
require 'models/essay'
require 'models/comment'
require 'models/person'
require 'models/reader'
@ -61,7 +62,7 @@ end
class HasManyAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :categories, :companies, :developers, :projects,
:developers_projects, :topics, :authors, :comments,
:people, :posts, :readers, :taggings, :cars
:people, :posts, :readers, :taggings, :cars, :essays
def setup
Client.destroyed_client_ids.clear
@ -1390,6 +1391,32 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
firm.clients.last
end
end
def test_custom_primary_key_on_new_record_should_fetch_with_query
author = Author.new(:name => "David")
assert !author.essays.loaded?
assert_queries 1 do
assert_equal 1, author.essays.size
end
assert_equal author.essays, Essay.find_all_by_writer_id("David")
end
def test_has_many_custom_primary_key
david = authors(:david)
assert_equal david.essays, Essay.find_all_by_writer_id("David")
end
def test_blank_custom_primary_key_on_new_record_should_not_run_queries
author = Author.new
assert !author.essays.loaded?
assert_queries 0 do
assert_equal 0, author.essays.size
end
end
def test_calling_first_or_last_with_find_options_on_loaded_association_should_fetch_with_query
firm = companies(:first_firm)