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

后端 未结 5 749
余生分开走
余生分开走 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:22

    In this case, I would probably do something relational, perhaps with STI if you wanted to have certain days where the business is closed (e.g. non-recurring closings). Here's a basic STI example:

    class Business < ActiveRecord::Base
      has_many :open_time_blocks
      has_many :closed_time_blocks
    
      def open?(time)
        # false if time is "inside" any of the closed_time_blocks
        # else is true if inside any of the open_time_blocks
        # else is false
      end
    
      def closed?(time)
        !open?
      end
    end
    
    # == Schema Information
    #
    # Table name: time_blocks
    #
    #  id          :integer         not null, primary key
    #  business_id :integer
    #  type        :string(255)
    #  start_at    :datetime
    #  end_at      :datetime
    #  created_at  :datetime
    #  updated_at  :datetime
    class TimeBlock < ActiveRecord::Base
      belongs_to :business
    end
    
    class OpenTimeBlock < TimeBlock; end
    class ClosedTimeBlock < TimeBlock; end
    

提交回复
热议问题