Skip to content

Instantly share code, notes, and snippets.

@nishio-dens
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nishio-dens/a0efb68a06d2a29c0bf6 to your computer and use it in GitHub Desktop.
Save nishio-dens/a0efb68a06d2a29c0bf6 to your computer and use it in GitHub Desktop.
Qiita:58ab6409f0da60a326e3 Squeelを使った実装
require 'active_record'
require 'active_support'
require 'squeel'
require 'minitest/autorun'
require 'logger'
require 'pry'
db_name = 'qiita_58ab6409'
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 'users', force: true do |t|
# t.integer "user_id" # user_id -> id に変更している
t.integer "period_id"
t.string "hoge_type"
end
create_table "user_balances", force: true do |t|
t.integer "period_id"
t.integer "user_id" # employee_id?
t.integer "amount"
end
create_table "user_insurances", force: true do |t|
t.integer "period_id"
t.integer "user_id" # employee_id?
t.string "user_type"
end
end
class UserBalance < ActiveRecord::Base
belongs_to :user
end
class UserInsurance < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :user_balances
has_many :user_balance_with_same_period,
-> { where { period_id == users.period_id } },
class_name: 'UserBalance'
has_many :user_insurances
has_many :user_insurance_with_same_period,
-> { where { period_id == users.period_id } },
class_name: 'UserInsurance'
# [注意]
# Originalでは employee_id となっている所を user_id に変更している
# また、user.user_id を user.id に変更している
#
# 以下SQLが生成される
#
# SELECT
# `users`.`id`
# FROM
# `users`
# LEFT OUTER JOIN
# `user_balances`
# ON `user_balances`.`user_id` = `users`.`id`
# AND `user_balances`.`period_id` = `users`.`period_id`
# LEFT OUTER JOIN
# `user_insurances`
# ON `user_insurances`.`user_id` = `users`.`id`
# AND `user_insurances`.`period_id` = `users`.`period_id`
# WHERE
# `users`.`hoge_type` != 'A'
# AND `user_balances`.`amount` > 0
# AND `user_insurances`.`user_type` = 'B'
def self.squeel_hogehoge_user_ids
User
.joins { user_balance_with_same_period.outer }
.joins { user_insurance_with_same_period.outer }
.where.not(hoge_type: 'A')
.where { user_balances.amount > 0 }
.where { user_insurances.user_type == 'B' }
.pluck(:id)
end
end
class CheckEagerLoad < MiniTest::Unit::TestCase
def setup
end
def teardown
User.delete_all
UserBalance.delete_all
UserInsurance.delete_all
end
def test_original_hogehoge_user_ids
# pryでsqlをチェック
binding.pry
User.squeel_hogehoge_user_ids
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment