user1301037 user1301037 - 2 months ago 7
Ruby Question

Rails - Method to return if a merchant are open

I have a Merchant model. The model accepts_nested_attributes for the Working Hour model.

Merchant Model

class Merchant < ApplicationRecord
has_many :working_hours, inverse_of: :merchant, dependent: :destroy
accepts_nested_attributes_for :working_hours, reject_if: :all_blank, allow_destroy: true
end


Working Hour model

class WorkingHour < ApplicationRecord
belongs_to :merchant
end


The working_hours table has:

class CreateWorkingHours < ActiveRecord::Migration[5.0]
def change
create_table :working_hours do |t|
t.integer :day
t.time :open_time
t.time :close_time
t.references :merchant, foreign_key: true
t.timestamps
end
end
end


The merchants can have more than one working_hour block by day
ex: 8:00 to 12:00 / 15:00 to 18:00.

I want to create a method to return if the merchant are opened or closed. How can I do that?

Answer

Update We've should've lost the self. part

try to add this to your merchant model

def open?
    self.working_hours.any? { |wh|
        (wh.open_time.hour..wh.close_time.hour).cover?(Time.current.hour)
    }
end
Comments