Reputation: 9715
In my customer controller I have two collection as follows:
The first one is to get a collection of Customers where the expiryDate column is having a valid date, as follows :
@customer_with_expirydate = Customer.where.not(expiryDate: nil)
The second one is to get a collection of Customers where the expiryDate column is nil or nnot present, as follows :
@customer_no_expirydate = Customer.where(expiryDate: nil)
Now I want to display the combined result of these two collection into a table structure, here one condition is like after listing all customers with expiryDate only customers without expiry need to be listed.
I need something like the following:
@all_customers = @customer_with_expirydate + @customer_no_expirydate
The important thing is that customers without expiry should be appended last.
Upvotes: 0
Views: 2938
Reputation: 6707
Let sort the customers by db query, it is more efficient than using array appending:
@ordered_customers = Customer.order('expiryDate DESC NULLS LAST')
So the customer with expiryDate = nil
will be at the end of your result!
Upvotes: 2
Reputation: 316
@Praveen Answer you had already given:
@all_customers = @customer_with_expirydate + @customer_no_expirydate
Returns All customers who has expiry date and then customers who does not have expiry date.
similarly:
@all_customers = @customer_no_expirydate + @customer_with_expirydate
Returns All customers who does not have expiry date and then customers who has expiry date.
Then you can loop @all_customers inside the table.
And if you can use only one query for this, then you should use:
@all_customers = Customer.order(expiryDate: :desc)
Upvotes: 2
Reputation: 1965
How about doing something simple with just one query? Something like:
@all_customers = Customer.order(expiryDate: :desc)
Upvotes: 3