在"How would you store a business's hours in the db/model of a Rails app",Simon Franzen提供了elegant solution(我是新手程序员,所以请注意,这对我来说似乎是这样)。Rails应用程序:如何在DB/Model中生成营业时间并显示当前状态?
我想知道如何在模型或控制器中实现is_open?
方法来反映查看页面上的“业务开放”或“业务接近”?
我不能直接问他,因为我没有足够的信誉点评论他的解决方案。
代码由西蒙·弗兰岑
模式:
# 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
型号:
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
@Iceman。这很可惜,但我没有试图解决这个问题。我只能从教程中编写代码。但我也意识到,最好的学习方式是让你的原创。从下次开始,我会首先尝试在这个帖子上提问,以获得更好的解决方案。 –