2017-02-15 24 views
0

"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 
+1

@Iceman。这很可惜,但我没有试图解决这个问题。我只能从教程中编写代码。但我也意识到,最好的学习方式是让你的原创。从下次开始,我会首先尝试在这个帖子上提问,以获得更好的解决方案。 –

回答

1

鉴于有样板Business存在哪些has_many :opening_hours然后open?(在Ruby中,我们并不需要过时is_因为我们可以用?最后定义方法来指示它返回布尔值)方法可以实现如下:

class Business < ActiveRecord::Base 
    has_many :opening_hours 

    # ... 

    def open? 
    opening_hours.where("? BETWEEN opens AND closes", Time.zone.now).any? 
    end 

    # ... 

end 
+1

or db agnostic'opening_hours.where(“?BETWEEN打开并关闭”,Time.zone.now).any?' – Iceman

+1

@Iceman谢谢你的建议 –

+0

@ Slava.K非常感谢你的回答。我想投你的答案,但我不能因为我的声誉得分低。 –

0

您可以尝试添加一天也进入它来检查是否今天业务是否打开?

def open? 
    opening_hours.where(day: Time.zone.now.wday).where('? BETWEEN opens AND closes', Time.zone.now).any? 
end 
相关问题