未验证 提交 36440720 编写于 作者: E Eileen M. Uchitelle 提交者: GitHub

Merge pull request #31819 from bpohoriletz/master

If association is a hash-like object preloading fails
......@@ -98,12 +98,11 @@ def preload(records, associations, preload_scope = nil)
# Loads all the given data into +records+ for the +association+.
def preloaders_on(association, records, scope, polymorphic_parent = false)
case association
when Hash
if association.respond_to?(:to_hash)
preloaders_for_hash(association, records, scope, polymorphic_parent)
when Symbol
elsif association.is_a?(Symbol)
preloaders_for_one(association, records, scope, polymorphic_parent)
when String
elsif association.respond_to?(:to_str)
preloaders_for_one(association.to_sym, records, scope, polymorphic_parent)
else
raise ArgumentError, "#{association.inspect} was not recognized for preload"
......
......@@ -1618,6 +1618,32 @@ def test_preloading_has_many_through_with_custom_scope
end
end
# Associations::Preloader#preloaders_on works with hash-like objects
test "preloading works with an object that responds to :to_hash" do
CustomHash = Class.new(Hash)
assert_nothing_raised do
Post.preload(CustomHash.new(comments: [{ author: :essays }])).first
end
end
# Associations::Preloader#preloaders_on works with string-like objects
test "preloading works with an object that responds to :to_str" do
CustomString = Class.new(String)
assert_nothing_raised do
Post.preload(CustomString.new("comments")).first
end
end
# Associations::Preloader#preloaders_on does not work with ranges
test "preloading fails when Range is passed" do
exception = assert_raises(ArgumentError) do
Post.preload(1..10).first
end
assert_equal("1..10 was not recognized for preload", exception.message)
end
private
def find_all_ordered(klass, include = nil)
klass.order("#{klass.table_name}.#{klass.primary_key}").includes(include).to_a
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册