activerecord-hackery / ransack

Object-based searching.
https://activerecord-hackery.github.io/ransack/
MIT License
5.66k stars 799 forks source link

Allow sorting using generated/virtual columns [Postgres] #1473

Open Tobias-Knudsen opened 8 months ago

Tobias-Knudsen commented 8 months ago

We're using Ransack in our Rails API. One of our Postgres tables has generated/virtuals columns, however they aren't included in the Ransack query, when I try and sort by these columns:

Here is my migration for adding the virtual column:

class AddGeneratedColumnsToVehicles < ActiveRecord::Migration[7.1]
  def change
    # Add virtual column to calculate horsepower
    add_column :vehicles, :horsepower, :virtual, type: :float, as: "ROUND((engine_power / 0.745699872)::numeric, 2)::float", stored: true
  end
end

Example:

ransack = Vehicle.ransack
ransack.sorts = ['horsepower DESC']
ransack.result.to_sql 
# OUTPUT: "SELECT "vehicles".* FROM "vehicles"

I would expect the output to be: "SELECT "vehicles".* FROM "vehicles" ORDER BY "vehicles"."horsepower" DESC

https://www.postgresql.org/docs/current/ddl-generated-columns.html