1

[ Rails: ActiveRecord db sort operation case insensitive ] shows how to perform a case-insensitive sort with ActiveRecord.

Rails: ActiveRecord db sort operation case insensitive

Table.order("lower(column) DESC")

The code I am working with requires column name to be represented as a symbol so that ActiveRecord will automatically expand it to "table"."column". This is required, because some queries contain a join statement with ambiguous column names.

GitLab CE: app/models/concerns/sortable.rb#L19-20

scope :order_name_asc, -> { reorder(name: :asc) }
scope :order_name_desc, -> { reorder(name: :desc) }

The table can't be hard coded into the method, because it is an abstract class used for several different tables.

Is there a way to get the table name like ActiveRecord does?

scope :order_name_asc, -> { reorder(%Q{LOWER("#{???}"."name") ASC}) }
scope :order_name_desc, -> { reorder(%Q{LOWER("#{???}"."name") DESC}) }

Is there a way to use a symbolic column name and LOWER together and let ActiveRecord expand the table name?


Edit: Fixed typo using backticks instead of double quotes in last example.

Community
  • 1
  • 1
Jared Deckard
  • 633
  • 6
  • 15

1 Answers1

1

ActiveRecord provides table_name method for models.

So

class User < ActiveRecord::Base
end
User.table_name
#=> "users"

Thus, this can be used in scope:

scope :order_name_asc, -> { reorder(%Q{LOWER("#{table_name}"."name") ASC}) }
Jared Deckard
  • 633
  • 6
  • 15
Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
  • Thanks for your quick response. I tried that, but it causes the records to no longer be sorted by their name. I think there is something I don't fully understand. I will try to debug and determine what value `table_name` is being resolved to. – Jared Deckard Mar 02 '17 at 16:24
  • I found the issue. I was using backticks which performs a system call in ruby! I had ES6 on the brain. Thanks for your help! – Jared Deckard Mar 02 '17 at 16:32
  • @JaredDeckard wow, my bad that i did not notice it. Good call! – Andrey Deineko Mar 02 '17 at 16:34
  • I added an edit to the question. It would be greatly appreciated if you could update your answer for future travelers. – Jared Deckard Mar 02 '17 at 16:36
  • @JaredDeckard i'll be near laptop in about 30 mins and will make sure to edit, sure! – Andrey Deineko Mar 02 '17 at 16:38