Skip to content

Instantly share code, notes, and snippets.

@senny
Created May 26, 2015 14:37
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 senny/1ae4d8ea7b0e269ed7a0 to your computer and use it in GitHub Desktop.
Save senny/1ae4d8ea7b0e269ed7a0 to your computer and use it in GitHub Desktop.
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'minitest/autorun'
require 'logger'
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.integer :likes
end
create_table :comments, force: true do |t|
t.integer :post_id
t.boolean :approved
end
end
class Post < ActiveRecord::Base
has_many :comments
has_many :approved_comments, -> { where(approved: true) }, class_name: "Comment"
end
class Comment < ActiveRecord::Base
belongs_to :post
end
class BugTest < Minitest::Test
def test_association_stuff
Post.includes(:comments, :approved_comments).where(approved_comments: {post_id: 1}).to_a
end
end
SELECT
"posts"."id" AS t0_r0,
"posts"."likes" AS t0_r1,
"comments"."id" AS t1_r0,
"comments"."post_id" AS t1_r1,
"comments"."approved" AS t1_r2,
"approved_comments_posts"."id" AS t2_r0,
"approved_comments_posts"."post_id" AS t2_r1,
"approved_comments_posts"."approved" AS t2_r2 FROM "posts"
LEFT OUTER JOIN "comments"
ON "comments"."post_id" = "posts"."id"
LEFT OUTER JOIN "comments" "approved_comments_posts"
ON "approved_comments_posts"."post_id" = "posts"."id" AND "approved_comments_posts"."approved" = ?
WHERE "comments"."post_id" = ? [["approved", true], ["post_id", 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment