Haymaker87
Haymaker87

Reputation: 529

Rails Active Record .where statement optimization

I'm building an ecommerce site and want to use an active record where statement to find shipments that are scoped to a certain supplier and certain shipment states. Here's what I have now:

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

I've found that this results in only 'shipped' statements get returned. I'd like it to display both shipped, and ready shipments. So far I can only get it to show one or the other, depending on if i put 'shipped' or 'ready' first in the query.

I'm guessing I have put the OR operator (||) in the wrong place, even though there are no errors. Can someone tell me a proper way to place OR operators in a condition in the where statement?

Thanks,

Upvotes: 1

Views: 112

Answers (2)

Mori
Mori

Reputation: 27779

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

Upvotes: 3

Haymaker87
Haymaker87

Reputation: 529

I figured out my answer as I was writing out the question a bit more. I wanted to share the answer in case anyone else comes across this. This seemed to do the trick:

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

I tested it in the console and it returned this SQL Output with shipments in both 'ready' and 'shipped' states:

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

Hope this can help others. Also, if you notice that this statement seems weird or inefficient I would really like to know.

Thanks!

Upvotes: 0

Related Questions