【问题标题】:check of business is open or not检查业务是否开放
【发布时间】:2016-07-18 12:41:28
【问题描述】:

我正在尝试检查商家的营业日期和营业时间,以确定其是否营业。

我的供应商部分中有此代码

%li
  = link_to shopping_supplier_path(supplier) do
    = content_tag :div, class: 'grid-block' do
      = content_tag :div, supplier.image_available, :class => 'small-3 grid-content'
      = content_tag :div, :class => 'small-9 grid-content' do
        %h4= supplier.name.truncate(30).titlecase
        = content_tag :div, class: 'grid-block' do
          .small-3.grid-content 9/10
          .small-3.grid-content $$
          .small-6.grid-content.text-right
            - SupplierTradingHour.open.includes(:supplier).each do |hour|
              = "#{hour.supplier.name} is open! It closes at #{hour.close_time}."

交易时间模型

class SupplierTradingHour < ActiveRecord::Base
  belongs_to :supplier

  scope :open, lambda { |day, time| { :conditions => ["self.weekday = ? AND self.open_time >= ? AND self.close_time < ?", day, time, time] } }

end

【问题讨论】:

  • 你忘了问问题。发生了什么?它的行为不符合预期?
  • ArgumentError at /shopping/suppliers 参数数量错误(0 代表 2)

标签: ruby-on-rails postgresql time trading


【解决方案1】:

您正在调用不带参数的 open 范围:SupplierTradingHour.open 但您的 :open 范围是带有两个参数 |day, time| 的 lambda 表达式,这也是您的代码失败的原因之一。

您的 SQL 逻辑表达式也不正确:open_time &lt;= ? AND close_time &gt; ?(注意运算符与您的相反)

在您的情况下,对于 DIY 实施(不使用第三方 gem),我建议这样做:

#app/models/trading_hour.rb
class TradingHour < ActiveRecord::Base

  belongs_to :supplier

  scope :open_now, -> (day, time) { where("weekday = ? AND open_time <= ? AND close_time > ?", day, time, time) }

end

然后在您的供应商模型中:

#app/models/supplier.rb
class Supplier < ActiveRecord::Base

  has_many :trading_hours

  def opening_status day, hour
    today_trading_hours = trading_hours.open_now(day, hour)
    if today_trading_hours.size > 0
      "Opened until #{today_trading_hours.first.close_time}H"
    else
      "Closed" 
    end 
  end
end

然后从你的角度来看电话

#if today is day 1
#and current hour is 12
supplier.opening_status(1, 12)

【讨论】:

  • 这似乎没有返回正确的 sql,因为 Merchant_id 被设置为 nil SELECT COUNT(*) FROM "trading_hours" WHERE "trading_hours"."merchant_id" = $1 AND (weekday = 0 AND open_time &lt;= '2016-05-29 03:01:59.377064' AND close_time &gt; '2016-05-29 03:01:59.377064') [["merchant_id", nil]]
【解决方案2】:

设置一个范围很好,但我可能只是用类似的东西定义我的@suppliers

@suppliers = Supplier.where("weekday = ? AND open_time > ? AND closing_time < ?", day, time, time)

另一种选择,如果您在不同情况下需要它的双方,将是编写一个实例方法is_open?

【讨论】:

  • 做这个添加方法,我得到的只是业务关闭,我需要datetruc当前时间吗?
【解决方案3】:

作为替代实现,您可能需要考虑使用以下 gem 来实现与营业时间相关的功能:

https://github.com/Intrepidd/working_hours

【讨论】:

  • 这不好,因为我在不同的供应商处有多个小时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 2019-08-19
  • 2021-11-20
  • 1970-01-01
相关资源
最近更新 更多