Shekhar Madanawat Shekhar Madanawat - 4 months ago 7
Ruby Question

Select and pluck in rails hitting same SQL query but with different result

I am hitting the following query from my rails console :

Listing.joins(:colors, :sizes, :product, :orders).pluck('colors.id', 'sizes.id', 'products.id', 'orders.id')
(4.5ms) SELECT colors.id, sizes.id, products.id, orders.id FROM "listings" INNER JOIN "colors" ON "colors"."listing_id" = "listings"."id" INNER JOIN "sizes" ON "sizes"."listing_id" = "listings"."id" INNER JOIN "products" ON "products"."id" = "listings"."product_id" INNER JOIN "orders" ON "orders"."listing_id" = "listings"."id"


and

Listing.joins(:colors, :sizes, :product, :orders).select('colors.id', 'sizes.id', 'products.id', 'orders.id')
Listing Load (4.6ms) SELECT colors.id, sizes.id, products.id, orders.id FROM "listings" INNER JOIN "colors" ON "colors"."listing_id" = "listings"."id" INNER JOIN "sizes" ON "sizes"."listing_id" = "listings"."id" INNER JOIN "products" ON "products"."id" = "listings"."product_id" INNER JOIN "orders" ON "orders"."listing_id" = "listings"."id"


and got the following results respectively :

[[2, 3, 1, 1], [2, 3, 1, 2], [2, 2, 1, 1], [2, 2, 1, 2], [2, 1, 1, 1], [2, 1, 1, 2], [3, 3, 1, 1], [3, 3, 1, 2], [3, 2, 1, 1], [3, 2, 1, 2], [3, 1, 1, 1], [3, 1, 1, 2], [4, 3, 1, 1], [4, 3, 1, 2], [4, 2, 1, 1], [4, 2, 1, 2], [4, 1, 1, 1], [4, 1, 1, 2]]


and

#<ActiveRecord::Relation [#<Listing id: 1>, #<Listing id: 2>, #<Listing id: 1>, #<Listing id: 2>, #<Listing id: 1>, #<Listing id: 2>, #<Listing id: 1>, #<Listing id: 2>, #<Listing id: 1>, #<Listing id: 2>, ...]>


Please help this is quiet confusing for me.

Answer

You are confused with the format of result provided by pluck and select. pluck return result in simple Array where as select return array of Active Record Relations. That is why you getting same result as different format.

Hope it will clear your doubt.

Output for pluck:

[[2, 3, 1, 1], [2, 3, 1, 2]..]

Output for select:

#<ActiveRecord::Relation[#<Listing id: 1>, #<Listing id: 2>..]
Comments