Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created October 4, 2022 10:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/54bbba23d2dca707716b716b42fb2070 to your computer and use it in GitHub Desktop.
Save JoshCheek/54bbba23d2dca707716b716b42fb2070 to your computer and use it in GitHub Desktop.
Experiment on ordering an active record query
require 'active_record'
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
ActiveRecord::Schema.define do
self.verbose = false
create_table :posts do |t|
t.string :title
t.string :status
end
end
Post = Class.new ActiveRecord::Base
ActiveRecord::VERSION::STRING # => "7.0.4"
Post.create!([
{ title: 'yo ho ho', status: 'draft' },
{ title: 'and a bottle of rum', status: 'published' },
])
Post.order(Arel.sql("status = 'draft' DESC, title ASC")).to_sql
# => "SELECT \"posts\".* FROM \"posts\" ORDER BY status = 'draft' DESC, title ASC"
Post.order(Arel.sql("status = 'draft'") => :desc, title: :asc).to_sql
# => "SELECT \"posts\".* FROM \"posts\" ORDER BY status = 'draft' DESC, \"posts\".\"title\" ASC"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment