Rails order array by params handling nil

Viewed 49

I am trying to order an array using params i receive from frontend. I receive the direction as descending true or false so I do

direction = params[:descending] ? :asc : :desc
Item.order(params[:sortBy] => direction )

If sortBy is name, i receive name desc, name asc, null desc

When it's null it searches for a null column. How do I handle it?

1 Answers

As order handles the values used to construct the ORDER BY clause, giving you kind of security against malicious input, you could just check the value received in the sortBy really is a column in the items table;

direction = params[:descending].presence ? :asc : :desc
column = params[:sortBy]
items = Item.all
items = items.order(column => direction) if column.in?(%w[id name etc])
Related