How would you store a business's hours in the db/model of a Rails app?

后端 未结 5 827
余生分开走
余生分开走 2021-01-31 05:43

I\'m creating a Rails app that will store the opening and closing hours for a business. Originally, I thought of simply using a text data type and letting it be free-form:

5条回答
  •  别跟我提以往
    2021-01-31 06:13

    I'm currently setting up a directory listing for a client and we want give the user more flexibility. So: Let the user set up blocks for days:

    We have a day (integer 1-7), opens (time), closes (time) and some shops or sights have summer and winter opening times, or they make vacations. According to schema.org you have to add a valid_from (datetime) and a valid_through (datetime).

    With this setup the user can create whatever he wants:

    # migration
    class CreateOpeningHours < ActiveRecord::Migration
      def change
        create_table :opening_hours do |t|
          t.integer :entry_id # your model reference
          t.integer :day
          t.time :closes
          t.time :opens
          t.datetime :valid_from
          t.datetime :valid_through
        end
      end
    end
    

    Example for the model:

    class OpeningHour < ActiveRecord::Base
    
      belongs_to :entry
    
      validates_presence_of :day, :closes, :opens, :entry_id
      validates_inclusion_of :day, :in => 1..7
      validate :opens_before_closes 
      validate :valid_from_before_valid_through 
    
      # sample validation for better user feedback
      validates_uniqueness_of :opens, scope: [:entry_id, :day]
      validates_uniqueness_of :closes, scope: [:entry_id, :day]
    
      protected
      def opens_before_closes
        errors.add(:closes, I18n.t('errors.opens_before_closes')) if opens && closes && opens >= closes
      end
    
      def valid_from_before_valid_through
        errors.add(:valid_through, I18n.t('errors.valid_from_before_valid_through')) if valid_from && valid_through && valid_from >= valid_through
      end
    
    end
    

    With that setup you can create easily a is_open? method in your model. Currently I did not setup the is_open? method, but if somebody needs, give me a hit! I think I will finish it in the next days.

提交回复
热议问题