简体   繁体   中英

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"

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM