Reputation: 7227
Lets say I have two Models a Business and a TimeSlot, and the relationship is that business has_many :timeslots
. each time slot has a day column which stores the dayname like 'Monday', 'Tuesday'
etc.
When I do
bussiness.time_slots
I get timeslots that are not sorted. I want the timeslots to be sorted by daynames (not alphabatically). times slots with 'Monday' come first than 'Tuesday' and so on.
I think SQL can't help me with this because the sorting is custom, I will need to sort after I read, but I am concerned about where to put which code
I can do something like
in my controller
b = current_business
TimeSlot.find_sorted_with_busines(b)
in my TimeSlot Model
def find_sorted_with_business(b)
b.time_slots
# sort timeslots using custom sorting here and return
end
but I dont like the idea of passing a business object or id to the TimeSlot model, I should be able to do something like
b = current_business
b.sorted_timeslots
how can I do this ?
Ideas on how to do custom sorting based on daynames are also welcome :)
Thanks
Upvotes: 1
Views: 840
Reputation: 21894
You should consider storing integers in the database instead of the day names. It would make things easier to sort, and probably a bit more performant.
Then, you can override the day
getter (to return the day name from the integer) and setter (to store the integer corresponding to the day name). You might not have to override the setter depending on what you get from your form.
Don't forget to have a custom validation, to check if the integer is between 1 and 7.
Upvotes: 2
Reputation: 15848
you CAN do custom sorting with sql:
SELECT *
FROM my_table
ORDER BY CASE
WHEN dayname = 'Monday' THEN 1
WHEN dayname = 'Tuesday' THEN 2
.
.
WHEN dayname = 'Sunday' THEN 7
ELSE 8
END
but the best is to use just an int for the column type like robin suggested and then use the number to get the day name and the order will simpler
Upvotes: 1