2015-05-06 48 views
1

我正在构建一个电子商务网站,并希望使用活动记录where语句来查找范围限定于特定供应商和某些装运状态的货物。这里是我现在有的:Rails Active Record .where语句优化

Spree::Shipment.where("stock_location_id = ? and "state = ?", spree_current_user.supplier.stock_locations.first.stock_location_id, 'shipped' || 'ready') 

我发现这只会导致'运送'语句得到返回。我希望它能显示已发货和已发货。到目前为止,我只能让它显示一个或另一个,具体取决于我是在查询中首先放置'运送'还是'准备好'。

我猜我已经把OR运算符(||)放在错误的地方,即使没有错误。有人能告诉我一种合适的方式来将OR操作符置于where语句中的条件吗?

感谢,

  • 布兰登

回答

3
id = spree_current_user.supplier.stock_locations 
     .first.stock_location_id 
Spree::Shipment.where(stock_location_id: id, state: %w[shipped ready]) 
+0

哇,快速响应。这看起来比我的回答更清洁。我会试一试! – Haymaker87

0

我想通了,我的回答是我写出来的问题多一点。我想分享答案,以防其他人遇到此问题。这似乎这样的伎俩:

Spree::Shipment.where("stock_location_id = ? and (state = ? or state = ?)", spree_current_user.supplier.stock_locations.first.id, 'shipped', 'ready') 

我在控制台测试,它在这两个“准备”和“发货”状态返回此SQL输出出货量:

Spree::Shipment Load (0.6ms) SELECT "spree_shipments".* FROM "spree_shipments" WHERE (stock_location_id = 8 and (state = 'shipped' or state = 'ready')) LIMIT 15 OFFSET 0 

希望这可以帮助其他人。另外,如果你注意到这个陈述看起来很奇怪或者效率低下,我真的很想知道。

谢谢!