How to make an order is applicable only to non-zero records, but still get all the records?

I want to order the result based on the condition.

for example

@redeemables = @business.redeemables.order(expiry_date: :desc)

I want all corrections with expiry_date => nilfirst what redeem order by desc

In other funds, redeemable, which have exipry_date < Date.current, should be below in order.

How can i do this? Thanks

+4
source share
4 answers

The easiest way to get what you want:

@redeemables = @business.redeemables.order("-expiry_date asc")
  • This will give you exactly the opposite of (expiry_date: asc)
  • This means descending ordered by expiry_date with zero first
+2

PostgreSQL, NULLS FIRST (vs. NULLS LAST) , SQL- (CASE ), relation + relation , , , .

@redeemables = @business.redeemables.order('(CASE WHEN expiry_date IS NULL THEN 1 ELSE 0 END) desc, expiry_date desc')
+2

You can do the following:

@redeemables_without_expiry = @business.redeemables.where("expiry_date IS NULL")
@redeemables_with_expiry = @business.redeemables.where("expiry_date IS NOT NULL").order(expiry_date: :desc)

@redeemables = @redeemables_without_expiry + @redeemables_with_expiry
0
source

Try something like this:

@redeemables = @business.redeemables.sort_by {|r| "#{r.expiry_date.blank?} #{r.desc}" }

Basically, this is sorting by concatenated string: whether the expiration date ( true/ false) and description are empty . (e.g. false item_description).

If you want to change the nil sort order expiry_dates, you can do the following:

@redeemables = @business.redeemables.sort_by {|r| "#{r.expiry_date.present?} #{r.desc}" }
0
source

Source: https://habr.com/ru/post/1607649/


All Articles