Skip to content

Instantly share code, notes, and snippets.

@cgunther
Created March 15, 2013 02:21
Show Gist options
  • Save cgunther/5167036 to your computer and use it in GitHub Desktop.
Save cgunther/5167036 to your computer and use it in GitHub Desktop.
When it tries to preload the active colors, it must first load the Skus, but it applies the order condition when querying for Skus
# A sample Gemfile
source "https://rubygems.org"
gem 'rails', '3.2.12'
gem 'sqlite3'
require 'rubygems'
require 'bundler/setup'
require 'active_record'
require 'logger'
ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:"
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :items do |t|
t.timestamps
end
create_table :colors do |t|
t.string :name
t.boolean :active, default: true
t.timestamps
end
create_table :skus do |t|
t.integer :item_id
t.integer :color_id
t.boolean :active
t.timestamps
end
end
class Item < ActiveRecord::Base
has_many :skus
has_many :active_colors, through: :skus, source: :color, class_name: 'Color', select: 'colors.*, lower(name)', conditions: { active: true, skus: { active: true } }, order: 'LOWER(name)', uniq: true
end
class Color < ActiveRecord::Base
end
class Sku < ActiveRecord::Base
belongs_to :color
belongs_to :item
end
i = Item.create
c2 = Color.create(name: 'm')
c1 = Color.create(name: 'a')
c3 = Color.create(name: 'z')
i.skus.create(color: c2)
i.skus.create(color: c1)
i.skus.create(color: c3)
items = Item.includes(:active_colors).to_a
expected_ids = [c1.id, c2.id, c3.id]
actual_ids = items.first.active_colors.map(&:id)
if expected_ids != actual_ids
raise "Expected #{expected_ids} to match #{actual_ids}"
else
puts "PASSED!"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment