使用Active Record(one2many)访问联合表的哈希值

问题描述 投票:0回答:1

一个商店has_many产品和一个产品belongs_to一个商店。车间具有opening_hoursclosing_hours列。每列存储一个哈希,如下所示:

opening_hours = {'Monday' => '12:00', 'Tuesday' => '13:00'}

依此类推

我正在使用当前日期和时间,并且我想检索所有存储的opening_hours小于当前时间且小于closing_hours的产品。基本上是商店营业时所有可用的产品。

我在控制器中做了类似的事情:

day_today = Date.today.strftime('%A')
time_now = Time.new.strftime('%H:%M')
@products = Product.joins(shop: [{opening_hours[day_today] < time_now, 
                                 {closing_hours[day_today] > time_now }])

编辑

这是将开放时间存储在数据库中的代码

hours_table = shop.search('table')
    opening_hours = {}
    closing_hours = {}
    hours_table.first.search('tr').each do |tr|
      cells = tr.search('td')
      day = cells.first.text.strip
      hours = cells.last.text.strip.tr('-', '').split
      opening_hours[day] = hours[0].to_time.strftime('%H:%M')
      closing_hours[day] = hours[1].to_time.strftime('%H:%M')
    end

shop = Shop.new(
        name: shop_name,
        opening_hours: opening_hours,
        closing_hours: closing_hours
      )
      shop.save

      new_product = Product.new(
        name: foo,
        description: foo,
        price: foo,
        company: 'foo',
      )
      new_product.shop = shop
      new_product.save

这是向Shop添加营业时间的迁移。营业时间也一样。

class AddOpeningHoursToShop < ActiveRecord::Migration[5.1]
  def change
    add_column :shops, :opening_hours, :json, default: {}
  end
end

这是向产品添加商店ID的迁移

class AddShopToProducts < ActiveRecord::Migration[5.1]
  def change
    add_reference :products, :shop, foreign_key: true
  end
end

任何猜测?

ruby-on-rails ruby postgresql activerecord jointable
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.