In "How would you store a business's hours in the db/model of a Rails app", Simon Franzen provided elegant solution (I'm novice programmer, so please mind that it seems like that to me).
And I want to know how to implement is_open?
method in model or controller to reflect the "Business is open" or "Business is close" on the view page?
I could not ask him directly because I don't have enough reputation points to comment on his solution.
Code by Simon Franzen
schema:
# 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
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