0

So i'm still trying to get to grips with Ruby & Rails and Postgres and i need to run a query but can't quite get my head round how to return the desired results

i have the following

ORDERS

the orders have many #ITEMS // as well as a TOTAL_PRICE variable

in the #ITEMS is an ORDERABLE_ID variable which refers to a #PRODUCT

i also have

USERS the users have many #ORDERS

I'm trying to run a query that will do the following

Check IF the current USER has an ORDER that contains an ITEM with ORDERABLE_ID == 71 with an ORDER TOTAL_PRICE > 40

OrderItem belongs_to :order 
OrderItem belongs_to :orderable 
Order has many :items, class_name "OrderItem"

1 Answer 1

1

Assuming:

  • a variable @product that has the id = 71
  • a variable @total_price that has the value 40
  • a variable/function called current_user
  • OrderItem belongs_to :order
  • OrderItem belongs_to :orderable, polymorphic: true
  • Order belongs_to :user

Then I believe it would be something like:

Order.
  joins(:items).
  where(items: {id: OrderItem.where(orderable: @product)}).
  where('total_price > ?', @total_price).
  where(user: current_user).
  any?
Sign up to request clarification or add additional context in comments.

1 Comment

OrderItem belongs_to :order // OrderItem belongs_to :orderable // Order has many :items, class_name "OrderItem"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.