gpt4 book ai didi

ruby-on-rails - Rails 应用程序 : How to generate business hours in DB/Model and shows current status?

转载 作者:行者123 更新时间:2023-12-04 07:35:32 25 4
gpt4 key购买 nike

"How would you store a business's hours in the db/model of a Rails app" , Simon Franzen 提供 elegant solution (我是新手程序员,所以请注意这对我来说似乎是这样)。

我想知道如何在模型或 Controller 中实现 is_open? 方法来在 View 页面上反射(reflect)“业务已打开”或“业务已关闭”?

我不能直接问他,因为我没有足够的声誉点来评论他的解决方案。

Simon Franzen 的代码

架构:

# 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

最佳答案

假设有一个模型 Business 存在,它 has_many :opening_hours 然后 open? (在 ruby​​ 中我们不需要过时的 is_ 前缀,因为我们可以在最后定义方法,用 ? 表示它返回 bool 值)方法可以实现如下:

class Business < ActiveRecord::Base
has_many :opening_hours

# ...

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

# ...

end

关于ruby-on-rails - Rails 应用程序 : How to generate business hours in DB/Model and shows current status?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42244494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com