Create a gist now

Instantly share code, notes, and snippets.

Invalid Includes
# require 'bundler'
# Bundler.require
require 'active_record'
require 'rails'
require 'minitest/autorun'
require 'logger'
db_name = 'rails-check'
ActiveRecord::Base.establish_connection adapter: 'mysql2', database: 'mysql', host: 'localhost'
ActiveRecord::Base.connection.drop_database db_name rescue nil
ActiveRecord::Base.connection.create_database db_name
ActiveRecord::Base.connection.close
ActiveRecord::Base.establish_connection adapter: 'mysql2', database: db_name, host: 'localhost'
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table 'products', force: true do |t|
t.string 'name' # 商品名
t.integer 'corporation_id' # 商品製造会社
t.integer 'shop_id' # 商品取扱店
end
create_table "shops", force: true do |t|
t.string 'name' # 店名
t.string 'corporation_id' # 本社
end
create_table "corporations", force: true do |t|
t.string "name" # 社名
end
end
class Product < ActiveRecord::Base
belongs_to :corporation
belongs_to :shop
end
class Shop < ActiveRecord::Base
has_one :product
belongs_to :corporation
end
class Corporation < ActiveRecord::Base
has_many :products
has_many :shops
end
class CheckEagerLoad < MiniTest::Unit::TestCase
def setup
Corporation.new(id: 1, name: 'DummyCompany').save
Corporation.new(id: 2, name: 'AShopHead').save
Shop.new(id: 1, name: 'AShop', corporation_id: 2).save
Product.new(id: 1, name: 'Product', corporation_id: 1, shop_id: 1).save
end
def teardown
Corporation.delete_all
Shop.delete_all
Product.delete_all
end
def test_no_eager_load
product = Product.joins(:corporation).joins(shop: :corporation).first
assert_equal 1, product.corporation.id
assert_equal 1, product.corporation_id
end
def test_eager_load_success_test
product = Product.includes(:corporation).references(:corporation).joins(:corporation).joins(shop: :corporation).first
assert_equal 1, product.corporation.id
assert_equal 1, product.corporation_id
end
# joinの順番を変えると失敗する
# eager loadが勘違い、どちらのcorporationをProductに結びつけていいか判断がつかないから?
def test_eager_load_fail_test
product = Product.includes(:corporation).references(:corporation).joins(shop: :corporation).joins(:corporation).first
# product.corporation.id と product.corporation_id が異なる結果となる
assert_equal 1, product.corporation.id
assert_equal 1, product.corporation_id
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment