Bryan Spence
Bryan Spence

Reputation: 133

Structure for a Rails Postgres Query

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"

Upvotes: 0

Views: 36

Answers (1)

jvillian
jvillian

Reputation: 20263

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?

Upvotes: 1

Related Questions