Skip to content

Instantly share code, notes, and snippets.

@yosiat
Created July 29, 2018 22:04
Show Gist options
  • Save yosiat/0e79260cbfeb7351d7f27d651ef3bf11 to your computer and use it in GitHub Desktop.
Save yosiat/0e79260cbfeb7351d7f27d651ef3bf11 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
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 "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Activate the gem you are reporting the issue against.
gem "activerecord", "5.2.0"
gem "sqlite3"
gem "byebug"
end
require "active_record"
require "logger"
require "byebug"
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.integer :another_post_id
t.string :title
end
end
class Post < ActiveRecord::Base
belongs_to :another_post, class_name: "Post", foreign_key: "another_post_id"
before_update :log_data
def update_all_posts(except_ids)
Post.where.not(id: except_ids).update(title: "hello")
end
def log_data
if id == 2
# as a result of update_all_posts, all queries for Post, have default query scope of "id != 1"
# so we can't find another_post (since it's id 1)
puts "Me: #{id}, Another Post (#{another_post_id}): #{another_post.inspect}"
# Post.count is 1, but actually it's 2
puts "Post.count: #{Post.count}"
end
end
end
ActiveRecord::Base.logger = Logger.new(STDOUT)
post1 = nil
post2 = nil
Post.transaction do
post1 = Post.create!
post2 = Post.create!
post2.another_post_id = post1.id
post2.save
end
post2.update_all_posts([post1.id])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment