Brad
Brad

Reputation: 8698

Rails Active Record complex query

I'm building an e-commerce app with rails and I have the following models:

Order
id:
user_id:
order_status:
subtotal:

OrderItem
id:
order_id:
product_id:
unit_price:
quantity:
total_price:

Product
id:
base_price:
discount:
price:(base_price less discount)

Each user can have one pending_order (order_status:1) and this order is then considered the "cart"

Then let's say a product get's its price updated, or a new discount amount.

I want to identify all the order_items that belong to a pending order and belong to the product being changed.

This is so that I can update the prices on these pending order items.

How can I write this query so that I can call it in the Product model before_save method?

I want something like (I know this is wrong but just to get an idea):

@items = OrderItem.where(order.order_status:1).where(product_id:self.id)

I think I need to use .joins() but I'm at a lose for how to get this working.

Can anyone help?

Upvotes: 0

Views: 65

Answers (1)

ste26054
ste26054

Reputation: 469

Something like this:

@items = OrderItem.joins(:order).where(product_id: 1, orders: { order_status: 1})

?

Upvotes: 2

Related Questions