Last active
April 12, 2023 15:20
-
-
Save astery/6137727 to your computer and use it in GitHub Desktop.
Eager loading and custom select.
This file contains hidden or 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
# Activate the gem you are reporting the issue against. | |
gem 'activerecord', '4.2.6' | |
require 'active_record' | |
require 'minitest/autorun' | |
require 'logger' | |
$logger = Logger.new(STDOUT) | |
# This connection will do for database-independent bug reports. | |
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') | |
ActiveRecord::Base.logger = $logger | |
ActiveRecord::Schema.define do | |
create_table :posts do |t| | |
t.string :name | |
t.string :teaser | |
end | |
create_table :comments do |t| | |
t.integer :post_id | |
t.string :content | |
t.string :user_name | |
end | |
end | |
class Post < ActiveRecord::Base | |
has_many :comments | |
has_many :comments_w_user_name, -> { select(:id, :user_name, :post_id) }, class_name: "Comment" | |
end | |
class Comment < ActiveRecord::Base | |
belongs_to :post | |
end | |
class BugTest < MiniTest::Unit::TestCase | |
def test_association_stuff | |
comment = Comment.create! | |
post = Post.create!(comments: [comment]) | |
# Deprecated since 4.0.0 and will not work >4.2 | |
# $logger.info "Post.includes(:comments).select(user_name)" | |
# Post.includes(:comments).select('posts.id', 'comments.id', 'comments.user_name').inspect | |
$logger.info "Post.includes(:comments_w_user_name)" | |
Post.includes(:comments_w_user_name).inspect | |
$logger.info "Post.includes(:comments).select(:user_name).references(:comments)" | |
Post.includes(:comments).select(:user_name).references(:comments).inspect | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can try it by your self just run with
ruby -Ilib:test gistfile1.rb
For whose who lazy (like me):