2015-05-06 45 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 

希望這可以幫助其他人。另外,如果你注意到這個陳述看起來很奇怪或者效率低下,我真的很想知道。

謝謝!