Skip to content

Instantly share code, notes, and snippets.

@mfazekas
Created February 17, 2017 09:15
Show Gist options
  • Save mfazekas/0e012b4dfc387afd704b517f98201366 to your computer and use it in GitHub Desktop.
Save mfazekas/0e012b4dfc387afd704b517f98201366 to your computer and use it in GitHub Desktop.
ransack double self join issue
# test-ransack-double-self-join.rb
# This is a stand-alone test case.
# Run it in your console with: `ruby test-ransack-scope-and-column-same-name.rb`
# If you change the gem dependencies, run it with:
# `rm gemfile* && ruby test-ransack-scope-and-column-same-name.rb`
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
# Rails master
gem 'rails', '~> 5.0.1'
#gem 'rails', github: 'rails/rails'
gem 'sqlite3'
gem 'byebug'
gem 'ransack', github: 'activerecord-hackery/ransack'
#gem 'ransack', '= 1.8.2' # github: 'activerecord-hackery/ransack'
#gem 'polyamorous', github: 'activerecord-hackery/polyamorous'
GEMFILE
system 'bundle install'
end
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'minitest/autorun'
require 'logger'
require 'ransack'
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
# Display versions.
message = "Running test case with Ruby #{RUBY_VERSION}, Active Record #{
::ActiveRecord::VERSION::STRING}, Arel #{Arel::VERSION} and #{
::ActiveRecord::Base.connection.adapter_name}"
line = '=' * message.length
puts line, message, line
ActiveRecord::Schema.define do
create_table :items, force: true do |t|
t.integer "parent_item_id"
t.integer "item_info_id"
end
create_table :item_infos, force: true do |t|
t.string "name"
end
end
class Item < ActiveRecord::Base
belongs_to :parent, foreign_key: :parent_item_id, class_name: "Item"
has_many :children, foreign_key: :parent_item_id, class_name: "Item"
belongs_to :item_info
end
class ItemInfo < ActiveRecord::Base
has_many :items
end
class BugTest < Minitest::Test
def test_parent_item_info_name
#require 'byebug' ; byebug
sql = ItemInfo.ransack({ items_parent_item_info_name_cont: "Foo" }).result.to_sql
puts sql
assert_equal(
"SELECT \"item_infos\".* FROM \"item_infos\" LEFT OUTER JOIN \"items\" ON \"items\".\"item_info_id\" = \"item_infos\".\"id\" LEFT OUTER JOIN \"items\" \"parents_items\" ON \"parents_items\".\"id\" = \"items\".\"parent_item_id\" LEFT OUTER JOIN \"item_infos\" \"item_infos_items\" ON \"item_infos_items\".\"id\" = \"parents_items\".\"item_info_id\" WHERE (\"item_infos_items\".\"name\" LIKE '%Foo%')", sql
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment