Skip to content

Instantly share code, notes, and snippets.

@danielgracia
Created June 11, 2014 18:59
Show Gist options
  • Save danielgracia/7fc63f39f7c8068ca12a to your computer and use it in GitHub Desktop.
Save danielgracia/7fc63f39f7c8068ca12a to your computer and use it in GitHub Desktop.
Unexpected behavior in pluck
gem 'activerecord', '4.1.0'
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::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :people do |t|
t.string :name
t.integer :age
end
create_table :pets do |t|
t.references :person
t.string :name
t.string :species
end
end
class Person < ActiveRecord::Base
has_many :pets
end
class Pet < ActiveRecord::Base
belongs_to :person
end
# Setup
peter, sally = Person.create [{ name: "Peter", age: 22 }, { name: "Sally", age: 25 }]
peter.pets.create [{ name: "Pluto", species: "Dog" }, { name: "Garfield", species: "Cat" }]
sally.pets.create [{ name: "Romeo", species: "Cat" }, { name: "Juliet", species: "Cat" }]
EXPECTED = [["Peter", "Garfield"], ["Sally", "Juliet"], ["Sally", "Romeo"]]
# NO_ALIAS = [["Garfield", nil], ["Juliet", nil], ["Romeo", nil]]
class BugTest < Minitest::Test
def pluck_fails_without_alias
plucked = Person.joins(:pets)
.where("pets.species = ?", "Cat")
.order("people.name ASC, pets.name ASC")
.pluck("people.name", "pets.name")
assert_equals plucked, EXPECTED
# assert_equals plucked, NO_ALIAS
end
def pluck_succeeds_with_alias
plucked = Person.joins(:pets)
.where("pets.species = ?", "Cat")
.order("people.name ASC, pets.name ASC")
.pluck("people.name", "pets.name as pet_name")
assert_equals plucked, EXPECTED
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment