Created
October 4, 2022 10:32
-
-
Save JoshCheek/54bbba23d2dca707716b716b42fb2070 to your computer and use it in GitHub Desktop.
Experiment on ordering an active record query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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