user1301037 user1301037 - 1 year ago 68
Ruby Question

Rails - Method to return if a merchant is 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

Working Hour model

class WorkingHour < ApplicationRecord
belongs_to :merchant

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

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 Source

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

try to add this to your merchant model

def open?
    self.working_hours.any? { |wh|
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download