Skip to content

Instantly share code, notes, and snippets.

@leods92
Last active August 29, 2015 13:58
Show Gist options
  • Save leods92/9940774 to your computer and use it in GitHub Desktop.
Save leods92/9940774 to your computer and use it in GitHub Desktop.
Demonstrating a Rails 4.0.4 bug.
# Tested on Rails 4.0.4
# Rails 4.1.0.rc2 has fixed it.
require 'active_record'
ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:"
ActiveRecord::Migration.create_table :library
ActiveRecord::Migration.create_table :books do |t|
t.string :name
t.integer :library_id
end
class Library < ActiveRecord::Base
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :libraries
end
puts Book.order(:name).to_sql
# SELECT "books".* FROM "books" ORDER BY "books"."name" ASC -> Great! √
puts Library.joins(:books).merge(Book.order(:name)).to_sql
# SELECT "libraries".* FROM "libraries" INNER JOIN "books" ON "books"."library_id" = "libraries"."id" ORDER BY "books"."name" ASC -> Great! √
puts Book.order(name: :desc).to_sql
# SELECT "books".* FROM "books" ORDER BY "books"."name" DESC -> Great! √
#
# The problem:
#
puts Library.joins(:books).merge(Book.order(name: :desc)).to_sql
# Expected:
# SELECT "libraries".* FROM "libraries" INNER JOIN "books" ON "books"."library_id" = "libraries"."id" ORDER BY "books"."name" DESC
# Returned:
# SELECT "libraries".* FROM "libraries" INNER JOIN "books" ON "books"."library_id" = "libraries"."id" ORDER BY "libraries"."name" DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment