Last active
July 24, 2019 16:13
-
-
Save Hirurg103/7b6bcffaf5478675d97c6e472cb17a4e to your computer and use it in GitHub Desktop.
Issue with joins in scopes in rails 5.2
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
begin | |
require "bundler/inline" | |
rescue LoadError => e | |
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler" | |
raise e | |
end | |
gemfile(true) do | |
source "http://rubygems.org" | |
gem "activerecord", "5.2.0" | |
gem 'sqlite3', '< 1.4' | |
gem "pry" | |
end | |
require "pry" | |
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 "posts", force: :cascade do |t| | |
t.string "title", null: false | |
t.text "body", null: false | |
end | |
create_table "comments", force: :cascade do |t| | |
t.integer "post_id", null: false | |
t.text "text", null: false | |
end | |
end | |
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
end | |
class Comment < ApplicationRecord | |
end | |
class Post < ApplicationRecord | |
has_many :comments, dependent: :destroy | |
has_one :last_comment, -> { | |
joins("LEFT JOIN posts on posts.id = comments.post_id") | |
.where(" | |
comments.id = ( | |
SELECT MAX(comments.id) FROM comments | |
WHERE comments.post_id = posts.id | |
)" | |
) | |
}, class_name: "Comment" | |
scope :with_last_comment, -> { joins(:last_comment) } | |
end | |
class IssueWithJoinsInScopesInRails_5_2_Test < Minitest::Test | |
def setup | |
@post = Post.create!(title: "Issue", body: "Issue with joins in scopes") | |
@comment = Comment.create!(post_id: @post.id, text: "How to fix it?") | |
end | |
def teardown | |
@post.destroy | |
end | |
def test_preload_last_comment_for_posts | |
post_with_last_comment = Post.with_last_comment[0] | |
assert_equal 1, post_with_last_comment.comment.count | |
end | |
end | |
test = IssueWithJoinsInScopesInRails_5_2_Test.new('Join error') | |
test.setup | |
test.test_preload_last_comment_for_posts | |
test.teardown |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment