0

I have a model called extra. Here how it looks like;

#<Extra id: nil, name: nil, price: nil, per: nil, compulsory: nil, online_payment: nil, payment_per_person: nil, is_included: nil, created_at: nil, updated_at: nil, user_id: nil>

I would like to first sort them by is_included where it is true. Then I want to sort where compulsory is true, lastly where compulsory is false. Then I want to combine them.

Basically, I want to group them because user can save them unordered. Then remove if anyone exists twice.

Shall I do it on the view or before_save callback?

Thanks

1 Answer 1

2

Extra.order('is_included desc, compulsory desc') will return your desired result and you should never execute SQL queries on view.

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

2 Comments

Can you also explain how it works by ordering desc, without putting true or false?
here's a link which would give you an idea. In sql true and false values are stored as 1 and 0. So, sorting is_included in descending order will sort the extras in descending order and then applying sorting on the resultant with compulsory attribute in descending order will give you the final result. The link I shared with you will help you in understanding the sorting of Null values with boolean values.

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.