2016-08-01 84 views
1

我從我的鐵軌控制檯打下面的查詢採摘:分別選擇和軌道擊中同一個SQL查詢,但有不同的結果

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" 

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" 

,並得到了以下結果:

[[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]] 

#<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>, ...]> 

請幫忙,這對我來說很安靜。

+1

普呂克返回一個數組中,選擇返回對象,在這種情況下,一些信息 –

回答

0

你困惑與pluckselect提供結果的格式。 pluck返回簡單數組結果,其中select返回活動記錄關係數組。這就是爲什麼你得到相同的結果作爲不同的格式。

希望它能清除你的疑惑。

輸出爲pluck

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

輸出爲select

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

你很困惑使用pluck和select。

select指定您想要的結果集中的哪個字段。但它將匹配的結果集作爲ActiveRecord對象數組返回。

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

儘管摘去做同樣的事情,也就是它運行的第一選擇與指定的屬性,但不是建立ActiveRecord的模型只從結果集撥弄出的屬性值,並把它們放在一個簡單的數組。因此,你只能看到結果值的數組,而不是數組對象:

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

雖然結果是一樣的,拔毛沒有按永遠不會創建活動記錄對象(的確,這只是它的一半) –

+0

@FrederickCheung你是對的,答案已經更新。 –

相關問題