Reputation: 173
Trying to learn Ruby and Spree
I've got a query in my controller that's running fine:
@products = Spree::LineItem.select("spree_line_items.id,
spree_variants.sku, spree_products.name, spree_line_items.quantity")
.joins(:order).joins(:variant).joins(:product)
.where(spree_orders: {state: 'complete', shipment_state: 'ready'})
When I run the query in my view
<% @products.each do |lineItem| %>
<%= lineItem.id %><br>
<% end %>
This works fine and spits out all of the ID's but I'm wanting to output the other bits, Sku, Name and Quantity which are all from other tables. How do I bring them in here?
If I reference them the same as the ID I get a DelegationError.
Upvotes: 0
Views: 424
Reputation: 421
To answer your query, you can do
@products = Spree::LineItem.select("spree_line_items.id,
spree_variants.sku AS variant_sku,
spree_products.name as product_name,
spree_line_items.quantity as quantity")
.joins(:order).joins(:variant).joins(:product)
.where(spree_orders: {state: 'complete', shipment_state: 'ready'})
Then access sku as lineItem.variant_sku
, name as lineItem.product_name
and quantity as lineItem.quantity
.
But the appropriate way to achieve this is
Spree::LineItem.joins(:order).includes(variant: :product)
.where(spree_orders: {state: 'complete', shipment_state: 'ready'})
And access attributes as lineItem.sku
, lineItem.name
, lineItem.quantity
We can do this because sku
and name
are delegated to variant
in line_item
model. This the same reason that you are getting DelegationError.
Upvotes: 2