Reputation: 221
I would like to sort data of my model base on a specific order.
Model: Grade
Table Column: category, value
values of category: Prelim, Midterm, Semi-finals, Finals
How do I sort the table Grade base on it's category with value of "Prelim, Midterm, Semi-Finals, Finals"?
Upvotes: 1
Views: 151
Reputation: 3656
If you dont want to replace them by numbers in the table as suggested by @titibouboul . You can just do.
class Grade
CATEGORY_IN_ORDER = ["Prelim", "Midterm", "Semi-Finals", "Finals"]
scope :ordered_by_category, lambda {"order(FIELD(category,#{CATEGORY_IN_ORDER.join(',')}))"}
end
then anywhere you can use this scope as:
Grade.ordered_by_category.where(YOUR_CRITERIA)
if you dont want to define scopes:
Grade.where(YOUR_CRITERIA).order("FIELD(category,#{CATEGORY_IN_ORDER.join(',')})")
More about order by FIELD syntax here: http://www.electrictoolbox.com/mysql-order-specific-field-values/
Upvotes: 4
Reputation: 1358
You should replace them by a number :
1 = Prelim
2 = Midterm
3 = Semi-finals
4 = Finals
and then sort them in the model like this :
class Grade
...
default_scope -> { order('category ASC') }
...
end
Upvotes: 0