Created
December 16, 2020 09:35
-
-
Save naoty/3c2e02d90743d6805da41e70dd515100 to your computer and use it in GitHub Desktop.
eager_loadでSELECTするカラムを絞れるか検証する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'activerecord' | |
gem 'sqlite3' | |
end | |
require 'active_record' | |
require 'minitest/autorun' | |
require 'logger' | |
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
ActiveRecord::Schema.define do | |
create_table :authors do |t| | |
t.string :name | |
end | |
create_table :books do |t| | |
t.string :title | |
t.integer :total_page_count | |
t.text :body | |
t.references :author | |
end | |
end | |
class Author < ActiveRecord::Base | |
has_many :books | |
has_many :books_metadata, -> { select(:id, :author_id, :title, :total_page_count) }, class_name: 'Book' | |
end | |
class Book < ActiveRecord::Base | |
belongs_to :author | |
end | |
class EagerLoadTest < Minitest::Test | |
def test_assert | |
author = Author.create(name: 'naoty') | |
author.books.create(title: 'dummy', total_page_count: 100, body: 'dummy') | |
sql1 = Author.eager_load(:books).to_sql | |
sql2 = Author.eager_load(:books_metadata).to_sql | |
assert sql1 != sql2 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
select
でカラムを制限した関連を定義してeager_load
に指定してみたけど効果なさそうだった。