From a01d164b948371c3405635713d9361f67d10a8bf Mon Sep 17 00:00:00 2001 From: Washington Luiz Date: Tue, 19 May 2015 00:18:44 -0300 Subject: Properly append preload / includes args on Merger Couldn't find other way to get the association name from a given class other than looping through `reflect_on_all_associations` reflections .. Noticed this one while looking at this example: ```ruby class Product < ActiveRecord::Base has_many :variants has_many :translations end class Translation < ActiveRecord::Base belongs_to :product end class Variant < ActiveRecord::Base belongs_to :product end class BugTest < Minitest::Test def test_merge_stuff product = Product.create! name: 'huhu' variant = Variant.create! product_id: product.id Translation.create! locale: 'en', product_id: product.id product_relation = Product.all .preload(:translations) .joins(:translations) .merge(Translation.where(locale: 'en')) .where(name: 'huhu') assert_equal variant, Variant.joins(:product).merge(product_relation).first end end ``` --- activerecord/test/cases/relations_test.rb | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) (limited to 'activerecord/test/cases/relations_test.rb') diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index b8e2041b6d..53dd8a39fe 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -17,7 +17,7 @@ require 'models/tyre' require 'models/minivan' require 'models/aircraft' require "models/possession" - +require "models/reader" class RelationTest < ActiveRecord::TestCase fixtures :authors, :topics, :entrants, :developers, :companies, :developers_projects, :accounts, :categories, :categorizations, :posts, :comments, @@ -621,6 +621,32 @@ class RelationTest < ActiveRecord::TestCase assert_equal 1, query.to_a.size end + def test_preloading_with_associations_and_merges + post = Post.create! title: 'Uhuu', body: 'body' + reader = Reader.create! post_id: post.id, person_id: 1 + comment = Comment.create! post_id: post.id, body: 'body' + + assert !comment.respond_to?(:readers) + + post_rel = Post.preload(:readers).joins(:readers).where(title: 'Uhuu') + result_comment = Comment.joins(:post).merge(post_rel).to_a.first + assert_equal comment, result_comment + + assert_no_queries do + assert_equal post, result_comment.post + assert_equal [reader], result_comment.post.readers.to_a + end + + post_rel = Post.includes(:readers).where(title: 'Uhuu') + result_comment = Comment.joins(:post).merge(post_rel).first + assert_equal comment, result_comment + + assert_no_queries do + assert_equal post, result_comment.post + assert_equal [reader], result_comment.post.readers.to_a + end + end + def test_loading_with_one_association posts = Post.preload(:comments) post = posts.find { |p| p.id == 1 } -- cgit v1.2.3