Skip to content

Instantly share code, notes, and snippets.

@klebervirgilio
Last active September 16, 2016 21:44
Show Gist options
  • Save klebervirgilio/1ceb189002d6575e31b192b9e6c00b0e to your computer and use it in GitHub Desktop.
Save klebervirgilio/1ceb189002d6575e31b192b9e6c00b0e to your computer and use it in GitHub Desktop.
Rails 4.2.7 - STI + HasManyThrough - Incorrect query being generated
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"
# Activate the gem you are reporting the issue against.
if ENV['AR'] == '5'
gem "activerecord", '5.0.0'
else
gem "activerecord", '4.2.7'
end
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"
require "logger"
# Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Schema.define do
create_table :destinations, force: true do |t|
t.integer :parent_id
t.string :type
t.string :name
end
create_table :attractions, force: true do |t|
t.string :name
end
create_join_table :attractions, :destinations, force: true do |t|
t.index :attraction_id
t.index :destination_id
end
end
class Destination < ActiveRecord::Base
end
class Continent < Destination
has_many :countries, foreign_key: :parent_id
has_many :states, through: :countries
has_many :cities, through: :states
end
class Country < Destination
belongs_to :continent, foreign_key: :parent_id
has_many :states, foreign_key: :parent_id
has_many :cities, through: :states
end
class State < Destination
belongs_to :country, foreign_key: :parent_id
has_many :cities, foreign_key: :parent_id
has_one :continent, through: :country
end
class City < Destination
belongs_to :state, foreign_key: :parent_id
has_one :country, through: :state
has_one :continent, through: :state
end
class BugTest < Minitest::Test
def test_ar_4_2_creates_incorrect_sql
south_america = Continent.where(name: 'South America').first_or_create!
brazil = Country.where(name: 'Brazil', parent_id: south_america.id).first_or_create!
sao_paulo_state = State.where(name: 'São Paulo', parent_id: brazil.id).first_or_create!
sao_paulo_city = City.where(name: 'São Paulo', parent_id: sao_paulo_state).first_or_create!
ActiveRecord::Base.logger = Logger.new(STDOUT)
assert_equal 1, south_america.city_ids.count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment