Reputation: 1099
I have an order clause on a model:
sorted = Teacher.order('teachers.first_name asc, teachers.last_name asc')
And several scope
where
methods called on sorted
afterwards.
Lastly, order is called on sorted
if a sort parameter is present.
The SQL statement built by Rails would have an order by
3 columns, (first_name
, last_name
and the last one coming from the param sent from the filters
).
The data set would never get to be ordered by the desired column, unless there were teachers with the same first and last name
.
Is there a way to prioritize the order column if the sorting parameter is present?
Upvotes: 0
Views: 118
Reputation: 114188
Lastly, order is called on
sorted
if a sort parameter is present.
I assume it looks somehow like this:
sorted = Teacher.order('teachers.first_name asc, teachers.last_name asc')
# ...
sorted = sorted.order(sort_param) if sort_param
Is there a way to prioritize the order column if the sorting parameter is present?
Just reorder your method calls accordingly:
sorted = Teacher.all
# ...
sorted = sorted.order(sort_param) if sort_param
sorted = sorted.order('teachers.first_name asc, teachers.last_name asc')
Upvotes: 3
Reputation: 11035
You could call reorder
on the relation if the parameter is present, but then you'd have to specify all the fields over again, so not very attractive.
Replaces any existing order defined on the relation with the specified order
User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC'
Nothing as far as I'm aware allows you to say "I want this order
value to appear before the previously set order
values"
Upvotes: 2