Module: Pluckeroid::ActiveRecord::Relation
- Included in:
- ActiveRecord::Relation
- Defined in:
- lib/pluckeroid/active_record/relation.rb
Instance Method Summary collapse
-
#pluck(*column_names) ⇒ Object
(also: #value_of, #values_of)
Same as
pluck_attributesbut returnsArraywith values of the specified column name. -
#pluck_attributes(*column_names) ⇒ Object
Performs select by column names as direct SQL query.
Instance Method Details
#pluck(*column_names) ⇒ Object Also known as: value_of, values_of
Same as pluck_attributes but returns Array with values of the specified column name.
Examples:
Person.pluck(:id) # SELECT people.id FROM people
=> [1, 2]
Person.pluck(:id, :name) # SELECT people.id, people.name FROM people
=> [[1, 'Obi-Wan'], [2, 'Luke']]
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/pluckeroid/active_record/relation.rb', line 37 def pluck(*column_names) flatten = column_names.size == 1 pluck_columns(column_names) do |attributes| values = attributes.map do |key, _| klass.type_cast_attribute(key, attributes) end if flatten values.first else values end end end |
#pluck_attributes(*column_names) ⇒ Object
Performs select by column names as direct SQL query. Returns Array of hashes each element of which contains specified column names as keys and the values of the column names as values. The values has same data type as column.
Examples:
Person.pluck(:id) # SELECT people.id FROM people
# => [{ 'id' => 1 }, { 'id' => 2 }]
Person.pluck_attributes(:id, :name) # SELECT people.id, people.name FROM people
# => [{ 'id' => 1, 'name' => 'Obi-Wan' }, { 'id' => 2, 'name' => 'Luke' }]
18 19 20 21 22 23 24 |
# File 'lib/pluckeroid/active_record/relation.rb', line 18 def pluck_attributes(*column_names) pluck_columns(column_names) do |attributes| attributes.each do |key, _| attributes[key] = klass.type_cast_attribute(key, attributes) end end end |