Skip to content

Instantly share code, notes, and snippets.

@manno
Created May 20, 2014 09:27
Show Gist options
  • Save manno/ffd48e0302a9ad51162e to your computer and use it in GitHub Desktop.
Save manno/ffd48e0302a9ad51162e to your computer and use it in GitHub Desktop.
AR missing join table alias
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'arel', github: 'rails/arel'
gem 'sqlite3'
GEMFILE
system 'bundle install'
end
require 'bundler'
Bundler.setup(:default)
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 :orders do |t|
end
create_table :deliveries do |t|
end
create_table :users do |t|
end
create_table :bookings do |t|
t.integer "user_id", null: false
t.integer "bookable_id"
t.string "bookable_type"
t.integer "booking_id"
end
end
class User < ActiveRecord::Base
has_many :bookings
has_many :orders, through: :bookings, source: :bookable, source_type: "Order"
has_many :deliveries, through: :bookings, source: :bookable, source_type: "Delivery"
scope :with_order, -> { joins(:orders).where(id: 1) }
scope :with_delivery, -> { joins(:deliveries).where(id: 1) }
scope :with_bookables, -> { with_order.with_delivery }
end
class Booking < ActiveRecord::Base
belongs_to :bookable, polymorphic: true
end
class Order < ActiveRecord::Base
has_one :booking, as: :bookable
end
class Delivery < ActiveRecord::Base
has_one :booking, as: :bookable
end
class BugTest < Minitest::Test
def test_polymorphic_join_conditions
user = User.create
user.deliveries.create
user.orders.create
assert_equal 1, User.with_order.count
assert_equal 1, User.with_delivery.count
assert_equal 1, User.with_bookables.count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment