0

As part of sorting based on priority_id column label names, I have done the below code:

 products = Product.where(id: pr_ids).order("priority_id IN(?)",ordered_priority_ids)

The below error is showing: ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR: syntax error at or near ")" LINE 1: ...ducts"."id" IN ($2, $3) ORDER BY priority_id IN(?), 4, 2, 3... ^ ):

Please help. Thanks

jissy
  • 463
  • 5
  • 20
  • Please check my answer to a similar question here https://stackoverflow.com/questions/67631962/rails-sort-by-specifc-order/67633594#67633594 – Yakov Jun 21 '21 at 13:12

1 Answers1

0
def self.order_by_priority_ids(ids)
  return self.where(:id => 0)  if ids.blank?
  values = []
  ids.each_with_index do |priority_id, index|
    values << "(#{priority_id}, #{index + 1})"
  end
  return self.joins("JOIN (VALUES #{values.join(",")}) as x (priority_id, ordering) ON #{table_name}.priority_id = x.priority_id").reorder('x.ordering')
end

And then you can use:

Product.where(id: pr_ids).order_by_priority_ids(ordered_priority_ids)
George
  • 1