Skip to content

Instantly share code, notes, and snippets.

@bobbus
Last active August 29, 2015 14:01
Show Gist options
  • Save bobbus/86e6044455e4cf6e182a to your computer and use it in GitHub Desktop.
Save bobbus/86e6044455e4cf6e182a to your computer and use it in GitHub Desktop.
AR bug when order on has_many :through
unless File.exists?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'sqlite3'
GEMFILE
system 'bundle'
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 :categories do |t|
end
create_table :products do |t|
end
create_table :category_product_links do |t|
t.references :category
t.references :product
t.integer :position
end
end
class Category < ActiveRecord::Base
has_many :category_product_links
has_many :products, -> { joins(:category_product_links).order('category_product_links.position') }, through: :category_product_links
# THE ONE BELOW IS WORKING but I believe it will instantiate all category_product_links which is not needed
# has_many :products, -> { includes(:category_product_links).order('category_product_links.position') }, through: :category_product_links
end
class Product < ActiveRecord::Base
has_many :category_product_links
has_many :categories, through: :category_product_links
end
class CategoryProductLink < ActiveRecord::Base
belongs_to :category
belongs_to :product
end
class BugTest < Minitest::Test
def test_load_category_with_product_includes
category_1 = Category.create!
category_2 = Category.create!
product_1 = Product.create!
product_2 = Product.create!
product_1.categories << category_1
product_2.categories << category_2
Category.includes(:products).to_a
# raise :
# ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: category_product_links.position: SELECT "products".* FROM "products" WHERE "products"."id" IN (1, 2) ORDER BY category_product_links.position
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment