Skip to content

Instantly share code, notes, and snippets.

@pekeler
Created January 11, 2014 22:38
Show Gist options
  • Save pekeler/8377939 to your computer and use it in GitHub Desktop.
Save pekeler/8377939 to your computer and use it in GitHub Desktop.
test case demonstrating uniq-through associations don't remove order anymore (which breaks postgresql)
# gem 'activerecord', '3.2.16' # works
gem 'activerecord', '4.0.2' # breaks
require 'active_record'
require 'minitest/autorun'
require 'logger'
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :posts do |t|
end
create_table :comments do |t|
t.integer :post_id
t.integer :user_id
end
create_table :users do |t|
end
end
class Post < ActiveRecord::Base
if Gem.loaded_specs["activerecord"].version.to_s >= "4"
has_many :comments, -> {order(:id)}
has_many :uniq_users_with_reorder, -> {reorder("").uniq}, :through => :comments, :source => :user
has_many :uniq_users_with_except, -> {except(:order).uniq}, :through => :comments, :source => :user
has_many :uniq_users, -> {uniq}, :through => :comments, :source => :user
else
has_many :comments, :order => :id
has_many :uniq_users, :uniq => true, :through => :comments, :source => :user
end
end
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
class User < ActiveRecord::Base
end
class BugTest < Minitest::Test
def test_uniq_through_removes_order_to_work_with_postgresql
post = Post.create!
if Gem.loaded_specs["activerecord"].version.to_s >= "4"
# reorder("") should work, i.e. overwrite order from relation
assert(!(post.uniq_users_with_reorder.to_sql =~ /order by/i), "generated sql includes ORDER BY")
# except(:order) should work, i.e. remove order from relation
assert(!(post.uniq_users_with_except.to_sql =~ /order by/i), "generated sql includes ORDER BY")
# possibly nice to have: uniq() automatically removes order from relation
assert(!(post.uniq_users.to_sql =~ /order by/i), "generated sql includes ORDER BY")
else
# just works: uniq() automatically removes order from relation
assert(!(post.uniq_users.to_sql =~ /order by/i), "generated sql includes ORDER BY")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment