Skip to content

Commit

Permalink
Document a difference between pluck and select [ci skip]
Browse files Browse the repository at this point in the history
Explain that `pluck` differs from `select` in that it does not construct `ActiveRecord` objects and thus model-level overrides are unavailable.
  • Loading branch information
egilburg committed Sep 4, 2013
1 parent beb5ea8 commit 956a27c
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions guides/source/active_record_querying.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -1476,14 +1476,45 @@ Client.select(:id).map(&:id)
Client.select(:id, :name).map { |c| [c.id, c.name] }
```

with
with:

```ruby
Client.pluck(:id)
# or
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.
Expand Down

0 comments on commit 956a27c

Please sign in to comment.