Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record_extension.rb

Class Method Summary collapse

Class Method Details

.pluck_tied_by_id(col_name) ⇒ Object

Person.pluck_tied_by_id(:name)

# => {1=>'David', 2=>'Jeremy', 3=>'Jose'}


7
8
9
10
# File 'lib/active_record_extension.rb', line 7

def pluck_tied_by_id(col_name)
  col_names = [:id] << col_name
  Hash[*self.pluck(*col_names).flatten]
end

.pluck_with_names(*col_names) ⇒ Object

Person.pluck_with_names(:id, :name)

# => [{:id=>1, :name=>'David'}, {:id=>2, :name=>'Jeremy'}, {:id=>3, :name=>'Jose'}]


14
15
16
17
18
19
20
21
# File 'lib/active_record_extension.rb', line 14

def pluck_with_names(*col_names)
  self.pluck(*col_names).map do |element|
    hash = {}
    col_names.map.with_index do |col, i|
      hash.merge!(col => element[i])
    end.uniq
  end.flatten
end