Search code examples
ruby-on-railsrubyransack

RubyOnRails Custom SQL Query in Ransack gem Advanced Forms


Click on image to see view

Ransack generated following query SELECT "sheets".* FROM "sheets" WHERE ("sheets"."id" > 5) but I want to implement formula in query SELECT "sheets".* FROM "sheets" WHERE (((score1 + score2)/2) > 5) Basically I want to compare formulas instead of attributes


Solution

  • In order to achieve this You would need to implement a custom ransacker.

    Something like

    class Sheet < ApplicationRecord
    
      ransacker :average_score do |parent|
        (parent.table[:score1] + parent.table[:score2]) / 2
      end
    end
    

    Then you can use general ransack syntax. e.g. average_score_gt or using the more advanced version ( I believe)

    Sheet.ransack(
      conditions: [{
        attributes: ['average_score'],
        predicate_name: 'gt',
        values: [5]
      }]
    )