From a6940f2a8307320599ded0dbcedd2375b392eaec Mon Sep 17 00:00:00 2001 From: Francesco Rodriguez Date: Sat, 19 May 2012 16:18:59 -0500 Subject: add CollectionProxy#select documentation --- .../active_record/associations/collection_proxy.rb | 57 +++++++++++++++++++++- 1 file changed, 55 insertions(+), 2 deletions(-) (limited to 'activerecord/lib/active_record') diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb index 1c22309d99..647d495d56 100644 --- a/activerecord/lib/active_record/associations/collection_proxy.rb +++ b/activerecord/lib/active_record/associations/collection_proxy.rb @@ -36,6 +36,59 @@ module ActiveRecord class CollectionProxy < Relation delegate :target, :load_target, :loaded?, :to => :@association + ## + # :method: select + # + # Works in two ways. + # + # *First:* Specify a subset of fields to be selected from the result set. + # + # class Person < ActiveRecord::Base + # has_many :pets + # end + # + # person.pets + # # => [ + # # #, + # # #, + # # # + # # ] + # + # person.pets.select(:name) + # # => [ + # # #, + # # #, + # # # + # # ] + # + # person.pets.select([:id, :name]) + # # => [ + # # #, + # # #, + # # # + # # ] + # + # Be careful because this also means you’re initializing a model + # object with only the fields that you’ve selected. If you attempt + # to access a field that is not in the initialized record you’ll + # receive: + # + # person.pets.select(:name).first.person_id + # # => ActiveModel::MissingAttributeError: missing attribute: person_id + # + # *Second:* You can pass a block so it can be used just like Array#select. + # This build an array of objects from the database for the scope, + # converting them into an array and iterating through them using + # Array#select. + # + # person.pets.select { |pet| pet.name =~ /oo/ } + # # => [ + # # #, + # # # + # # ] + # + # person.pets.select(:name) { |pet| pet.name =~ /oo/ } + ## # :method: find # Finds an object in the collection responding to the +id+. Uses the same @@ -51,7 +104,7 @@ module ActiveRecord # # #, # # #, # # # - # # ] + # # ] # # person.pets.find(1) # => # # person.pets.find(4) # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=4 @@ -284,7 +337,7 @@ module ActiveRecord :sum, :count, :size, :length, :empty?, :any?, :many?, :include?, :to => :@association - + def initialize(association) @association = association super association.klass, association.klass.arel_table -- cgit v1.2.3