rails populate field in model depending on another field -
i need order days name, have table field called day_name, select can sunday, monday, etc.
so thinking add field table (day_order) when enters sunday on day_name populates day_order 1, when enters monday in day_name, don't know how populate day_order depending on day_name.
there option, should when picks "sunday" in day_name, store 1 instead, , change again when read table. don't know how neither.
so need help, trying order array storing days in order , try make custom order, think easy (and faster) other way model. can sort easily.
pd: i'm looking @ before_save filter in model
i solved it,
finally added integer day_order field timetables table. , made presence mandatory
validates :day_order, presence: true
then limited in model number can added field with
def day_order_enum [1, 2, 3, 4, 5, 6] end
and next step doing before_validation method
before_validation :set_day_order def set_day_order if self.day_name == "monday" self.day_order = 1 elsif self.day_name == "tuesday" self.day_order = 2 elsif self.day_name == "wednesday" self.day_order = 3 elsif self.day_name == "thursday" self.day_order = 4 elsif self.day_name == "friday" self.day_order = 5 elsif self.day_name == "saturday" self.day_order = 6 end end
finally made scope ordering days day_order field
scope :day_asc_order, ->{ order('day_order asc') }
and used day_asc_order when listing.
probably not best way it, works. if knows better way , want share it, thank him/her.
ps: don't need sunday it's not on list on purpose ;)
Comments
Post a Comment