Ruby: How to store and display a day of the week?

后端 未结 4 1793
梦毁少年i
梦毁少年i 2020-12-31 08:58

I\'m relatively new to Ruby. I need to keep track of a day of the week on my activity model. The code that I have so far doesn\'t seem like the most elegant solution. I am w

相关标签:
4条回答
  • 2020-12-31 09:26

    The easiest way (RoR) is using the built-in constant:

    Date::DAYS_INTO_WEEK
    # => 
    {:monday=>0,
     :tuesday=>1,
     :wednesday=>2,
     :thursday=>3,
     :friday=>4,
     :saturday=>5,
     :sunday=>6}
    
    0 讨论(0)
  • In the latest versions you can define an enum with that constant and then use it for different things:

    In migration, day_of_week is integer

    In model:

    enum :day_of_week => Date::DAYS_INTO_WEEK

    And then you can use searches in model

    Model.day_of_weeks.keys[0..4] will return ['monday', 'tuesday', .... 'friday']

    Model.monday is equivalent to Model.where("day_of_week = ?", 'monday')

    http://api.rubyonrails.org/classes/ActiveRecord/Enum.html

    0 讨论(0)
  • 2020-12-31 09:41

    Ruby's Date class already has a constant defined that holds the name of the days in an array: Date::DAYNAMES.

    For example, you could do something like:

    days = []
    Date::DAYNAMES.each_with_index { |x, i| days << [x, i] }
    

    I don't know if I'd necessarily say that this is better, but you can definitely leverage what is already available to you.

    0 讨论(0)
  • 2020-12-31 09:44

    To keep it simplest, I would :

    • save the plain text name of the day instead of number in @activity.day
    • add a constant DAYS, it can live on your Activity model but may move to somewhere else in the future

    Then it will looks like :

    Model

    DAYS = ['monday','tuesday',...]
    
    validates_inclusion_of :day, :in => DAYS
    

    View : form

    <%= f.collection_select :day, Activity::DAYS, :to_s, :humanize %>
    

    View : display

    <%= activity.day.humanize %>
    

    Keep it simple and you will extend it later if needed :)

    0 讨论(0)
提交回复
热议问题