Question

Disclaimer: I'm new to Rails.

What I'm trying to do is this in the long form:

user = Spree::User.find(2)
cart = Spree::Order.where(state: "cart", user_id: user.id)
line_item = Spree::LineItem.where(order_id: cart.last.id).map { |order| order.variant_id}
variant = Spree::Variant.find(line_item).map { |order| order.product_id }
Spree::Product.find(variant).map { |product| product.name }

What happens is it goes into the DB, finds the user, gets an order where their state is in cart. Then goes and finds its line item. Goes over to find the "variant" data to find out what products are included. Then over to the products page to tell me all products in a users cart.

This looks ugly and garjumbled. You wouldn't happen to know a way to refactor it and not do so much querying?

Was it helpful?

Solution

If you look at Spree Order States, it's not that you have multiple orders in different states, just one order that could be in one particular state.

It really depends on Spree::User. I can't find documentation and/or source for Spree::User, but mentions to a certain LegacyUser. Since in the comments you mentioned you have a custom build, you need to check the actual code for Spree::User and see if a user can have one or many orders, and if there's already a method for selecting cart state orders.

So if Spree::User has one order:

order = user.order
order.variants.map(&:name)

Else:

order = user.orders.where(state: "cart")
order.variants.map(&:name)

There could be a method to get the order you need from the user in the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top