1

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"?

2 Answers 2

4

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/

Sign up to request clarification or add additional context in comments.

2 Comments

@fujisan i dont think this is dependent of rails version. Just try Grade.where("category is not null").order("FIELD(category,#{CATEGORY_IN_ORDER.join(',')})") . Its pure mysql syntax.
I have already used it as my default scope. Thanks again for the solution.
0

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

3 Comments

Prelim, Midterm, Semi-finals and finals are values of category so I won't be able to change them right now.
I would not recommend using default_scope: rails-bestpractices.com/posts/806-default_scope-is-evil
default_scope has gotten less crappy in Rails 4, for the record.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.