is there any difference between where clause and using association object for performance

Viewed 57

for example we have association between products and order. Will there be any difference between these two queries that are written below . Are thy both same in execution time and performance wise

@products = @order.products
@products = Product.where(order_id: @order.id)

or can we improve this above query in any way ?

2 Answers

They do the same thing. If you run the query in the console, you will see something like this

Order Load (0.3ms) SELECT "orders".* from "orders" WHERE "orders"."id" = $1 LIMIT $2, [["ID", 1], "LIMIT", 1]
Product Load (0.3ms) SELECT "products".* from "products" WHERE "products"."order_id" = $1 [["ORDER_ID", 1]]

They both do the same thing and the performance is the same. These queries will use the order id to get the products from the product table. The related sql query will be the same.

The only difference is that if you have used eager loading before loading the order then this query will run in memory as the related products would already be loaded: @products = @order.products

Related