【问题标题】:Rails Active Record .where statement optimizationRails Active Record .where 语句优化
【发布时间】:2015-05-06 02:32:23
【问题描述】:

我正在构建一个电子商务网站,并希望使用活动记录 where 语句来查找范围为特定供应商和特定货件状态的货件。这是我现在拥有的:

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

我发现这只会返回“已发货”语句。我希望它同时显示已发货和准备好的货物。到目前为止,我只能让它显示一个或另一个,这取决于我是否在查询中将“已发货”或“准备好”放在首位。

我猜我把 OR 运算符 (||) 放在了错误的位置,即使没有错误。有人能告诉我在 where 语句的条件中放置 OR 运算符的正确方法吗?

谢谢,

  • 布兰登

【问题讨论】:

    标签: ruby-on-rails rails-activerecord where


    【解决方案1】:
    id = spree_current_user.supplier.stock_locations
           .first.stock_location_id
    Spree::Shipment.where(stock_location_id: id, state: %w[shipped ready])
    

    【讨论】:

    • 哇,反应快。这看起来比我的回答要干净得多。我试试看!
    【解决方案2】:

    当我写出更多的问题时,我想出了我的答案。我想分享答案,以防其他人遇到这个问题。这似乎可以解决问题:

    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
    

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

    谢谢!

    【讨论】:

      猜你喜欢
      • 2016-02-25
      • 2013-09-26
      • 1970-01-01
      • 2018-05-08
      • 2015-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      相关资源
      最近更新 更多