Skip to content

Instantly share code, notes, and snippets.

@pjambet
Last active February 9, 2023 23:54
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 pjambet/e5ccd8ba4cc1a5d22fe29af3884d1c2d to your computer and use it in GitHub Desktop.
Save pjambet/e5ccd8ba4cc1a5d22fe29af3884d1c2d to your computer and use it in GitHub Desktop.
Rails 7.0 unscope & all_queries: true for update/destroy issue
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem "rails", github: "rails/rails", branch: "main"
gem "sqlite3"
end
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|
end
create_table :comments, force: true do |t|
t.integer :post_id
t.timestamps
end
end
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
default_scope -> { where(post_id: 1) }, all_queries: true
end
class BugTest < Minitest::Test
def test_association_stuff
post1 = Post.create!
comment1 = post1.comments.create!
post2 = Post.create!
comment2 = post2.comments.create!
assert comment1.touch # query includes WHERE post_id = 1
comment2.touch # query includes WHERE post_id = 1, returns nothing and is a no-op
refute_equal Comment.unscoped.find(comment2.id).updated_at, comment2.updated_at
Comment.unscoped { comment2.touch } # query includes WHERE post_id = 1, returns nothing and is a no-op
assert_equal Comment.unscoped.find(comment2.id).updated_at, comment2.updated_at
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment