Rails 3.2 ,ActiveRecord 實作 Pluck (採摘)
2011-12-05 23:52:07 +0800 由 xdite
在 Ruby on Rails 節點 中發起
最後由 hooopo 於2011-12-09 16:16:18 +0800回應
, 573次閱讀
以往透過 ActiveRecord 拉資料,都是 SELECT *。Rails 3.2 新增機制 Pluck,可以只「摘」出特定欄位了!
請看 commit : http://github.com/rails/rails/commit/a382d60f6abc94b6a965525872f858e48abc00de
截至 2011-12-09 16:16:18 +0800,共收到 13 條回應
chitsaou
1樓, 於2011-12-06 00:15:50 +0800回應
剛剛在想這跟 select(:field)
有何不同,所以實際操作了一下。
ree-1.8.7-2011.03 :009 > Post.select("id")
Post Load (0.2ms) SELECT id FROM "posts"
=> [#<Post id: 19>, #<Post id: 20>, #<Post id: 21>, #<Post id: 22>, #<Post id: 23>, #<Post id: 24>, #<Post id: 25>, #<Post id: 27>, #<Post id: 29>, #<Post id: 30>, #<Post id: 31>, #<Post id: 32>]
拿到的東西是 Post 的 instances ,每個 instance 只有設定 id
這個 instance variable 而已。
如果要拿 id
array 的話,得要 .map(&:id)
。
ree-1.8.7-2011.03 :013 > Post.select("id").map(&:id)
Post Load (0.2ms) SELECT id FROM "posts"
=> [19, 20, 21, 22, 23, 24, 25, 27, 29, 30, 31, 32]
而這條 commit 的 pluck(:id)
就是幫你變成一條 array of value of field(s) 。
hechian
2樓, 於2011-12-06 00:46:15 +0800回應
所以也就是說,摘出來的直接就是資料,而非Object囉?
hSATAC
6樓, 於2011-12-07 13:22:58 +0800回應
應該一樣快吧,只是寫起來比較短比較好看。
hlb
8樓, 於2011-12-09 13:25:56 +0800回應
看成 ActiveRecord 實作 Plurk...
xdite
10樓, 於2011-12-09 15:21:52 +0800回應
我在打這篇時,就差一點打錯...
hooopo
11樓, 於2011-12-09 15:45:51 +0800回應
#10楼 @xdite 通过邮件点击过来链接有错误 链接到了:http://topics/58
xdite
12樓, 於2011-12-09 16:01:38 +0800回應
可以幫我發個 issue 上 github 嗎?thanks