aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEugene Gilburg <eugene.gilburg@gmail.com>2013-09-04 02:04:36 -0700
committerEugene Gilburg <eugene.gilburg@gmail.com>2013-09-04 09:51:34 -0700
commit956a27ccd6aa119a5a64aa5714fc629c9d3317eb (patch)
tree6503bf8f999605647eddde1e47126f0709f3e87d
parentbeb5ea8468e7f629b32252efd644bc68d1b34237 (diff)
downloadrails-956a27ccd6aa119a5a64aa5714fc629c9d3317eb.tar.gz
rails-956a27ccd6aa119a5a64aa5714fc629c9d3317eb.tar.bz2
rails-956a27ccd6aa119a5a64aa5714fc629c9d3317eb.zip
Document a difference between pluck and select [ci skip]
Explain that `pluck` differs from `select` in that it does not construct `ActiveRecord` objects and thus model-level overrides are unavailable.
-rw-r--r--guides/source/active_record_querying.md35
1 files changed, 33 insertions, 2 deletions
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index ba0dc6d9eb..5aa935a155 100644
--- a/guides/source/active_record_querying.md
+++ b/guides/source/active_record_querying.md
@@ -1466,7 +1466,7 @@ Client.pluck(:id, :name)
# => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
```
-`pluck` makes it possible to replace code like
+`pluck` makes it possible to replace code like:
```ruby
Client.select(:id).map { |c| c.id }
@@ -1476,7 +1476,7 @@ Client.select(:id).map(&:id)
Client.select(:id, :name).map { |c| [c.id, c.name] }
```
-with
+with:
```ruby
Client.pluck(:id)
@@ -1484,6 +1484,37 @@ Client.pluck(:id)
Client.pluck(:id, :name)
```
+Unlike `select`, `pluck` directly converts a database result into a Ruby `Array`,
+without constructing `ActiveRecord` objects. This can mean better performance for
+a large or often-running query. However, any model method overrides will
+not be available. For example:
+
+```ruby
+class Client < ActiveRecord::Base
+ def name
+ "I am #{super}"
+ end
+end
+
+Client.select(:name).map &:name
+# => ["I am David", "I am Jeremy", "I am Jose"]
+
+Client.pluck(:name)
+# => ["David", "Jeremy", "Jose"]
+```
+
+Furthermore, unlike `select` and other `Relation` scopes, `pluck` triggers an immediate
+query, and thus cannot be chained with any further scopes, although it can work with
+scopes already constructed earlier:
+
+```ruby
+Client.pluck(:name).limit(1)
+# => NoMethodError: undefined method `limit' for #<Array:0x007ff34d3ad6d8>
+
+Client.limit(1).pluck(:name)
+# => ["David"]
+```
+
### `ids`
`ids` can be used to pluck all the IDs for the relation using the table's primary key.