Reputation: 1287
I have an Order model which has the following attributes:
submitted_date :date
completed_date :date
accepted_date :date
Im using these fields to determine the order's status with the following code block:
def status
if completed_date.present?
"Fulfilled"
elsif accepted_date.present? && submitted_date.present? && completed_date.blank?
"Accepted"
elsif submitted_date.present? && accepted_date.blank? && completed_date.blank?
"Submitted"
else
"Open"
end
end
I totally spaced it when building the application and I didnt realize that the user would want to see the results ordered in the following order:
Open, Submitted, Accepted, Fulfilled
I probably should have used an integer field to use as an enum to determine the status of an order, but I've built up a lot of functionality around the above structure.
What Im wondering is if it's possible to order the query so that the results are ordered by the above arbitrary order?
Upvotes: 0
Views: 110
Reputation: 325
I think ordering by the most complete status would do the trick. Open order will have a nil date so should be order properly
Order.order(submitted_date: :desc, completed_date: :desc, accepted_date: :desc)
playing with the :desc/:asc
option and .reverse
should do the trick.
For another iteration, one approach would be to have a state machine, having a status enum column, a date for each step. validating the required condition would progress the order to the next step
Upvotes: 1