Last active
February 9, 2016 19:48
-
-
Save dougbarth/44eb4adc28f8d6026322 to your computer and use it in GitHub Desktop.
Gotcha with STI and unscoped queries against the base class
This file contains 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 'https://rubygems.org' | |
gem 'rails', github: 'rails/rails' | |
gem 'arel', github: 'rails/arel' | |
gem 'rack', github: 'rack/rack' | |
gem 'sprockets', github: 'rails/sprockets' | |
gem 'sprockets-rails', github: 'rails/sprockets-rails' | |
gem 'sass-rails', github: 'rails/sass-rails' | |
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| | |
t.string :type | |
t.timestamps | |
end | |
end | |
class Post < ActiveRecord::Base | |
def self.find_and_modify(pid) | |
p = Post.find(pid) | |
p.touch | |
p.save! | |
end | |
end | |
class SubPost < Post | |
after_save :query_subclass | |
def query_subclass | |
query_sql = SubPost.all.to_sql | |
unless query_sql.include?(%|"posts"."type" IN ('SubPost')|) | |
raise "Expected query to scope by type: #{query_sql}" | |
end | |
end | |
end | |
class BugTest < Minitest::Test | |
def setup | |
@sub = SubPost.create! | |
end | |
# Passes under Rails master | |
def test_query_in_same_frame_should_use_sti_where_clause | |
p = Post.unscoped.find(@sub.id) | |
p.touch | |
p.save! | |
end | |
# FAILS under Rails master | |
def test_query_in_subframe_should_use_sti_where_clause | |
Post.unscoped.find_and_modify(@sub.id) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment