我明白你的意图,但坦率地说,我认为这不会以一种直接、简单的方式对你有用。 (根据经验,在 ruby 和 rails 中,如果它不简单,您可能不会使用 ruby/rails 方式)。
我为什么知道这个?因为我之前尝试过做与你想用 hstore 做的事情非常相似的事情,但没有运气:
Can I use ActiveRecord relationships with fields from an Hstore?
作为一个更好的解决方案(最终对我来说是什么),请考虑制作一个中间模型来匹配 Shops 到 Products,(也许你会想将此中间模型命名为 @ 987654325@,带有连接表 shops_products,但名称由您决定)然后使用带有 has_many through: 关系的中间模型连接两个模型,详情如下:
http://edgeguides.rubyonrails.org/association_basics.html#the-has-many-through-association
类似:
class Shop << ActiveRecord::Base
has_many :shop_products
has_many :products, through: :shop_products
end
class ShopProduct << ActiveRecord::Base
belongs_to :shop
belongs_to :product
end
class Product << ActiveRecord::Base
has_many :shop_products
has_many :shops, through: :products
(关于如何在链接中创建所有这些的更多信息,我建议阅读)
现在您将建立一个关联,因此您可以获得:
Shop.find_by_id(1).products
Product.find_by_id(1).shops
最后,我认为你可以使用 ActiveRecord scopes 来解决你需要解决的第二个计算问题(即求过去每天的价格)。
理想情况下,范围将允许您执行以下查询:
Shop.products.active_yesterday
class Product << ActiveRecord::Base
scope active_yesterday -> { where('updated_at BETWEEN ? AND ?', 1.day.ago.beginning_of_day, 1.day.ago.end_of_day) }
has_many :shop_products
has_many :shops, through: :shop_products
end
我的所有代码都不是生产就绪的,也没有经过测试,但我认为我的示例和链接应该足以让你走上正确的道路。
如果您需要更多帮助,请告诉我,我会尽力提供帮助。