跳到內容 跳到搜尋

Active Record 計算

方法
A
C
I
M
P
S

實例公開方法

async_average(column_name)

average 相同,但會非同步執行查詢並傳回 ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 122
def async_average(column_name)
  async.average(column_name)
end

async_count(column_name = nil)

count 相同,但會非同步執行查詢並傳回 ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 108
def async_count(column_name = nil)
  async.count(column_name)
end

async_ids()

ids 相同,但會非同步執行查詢並傳回 ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 409
def async_ids
  async.ids
end

async_maximum(column_name)

maximum 相同,但會非同步執行查詢並傳回 ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 152
def async_maximum(column_name)
  async.maximum(column_name)
end

async_minimum(column_name)

minimum 相同,但會非同步執行查詢並傳回 ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 137
def async_minimum(column_name)
  async.minimum(column_name)
end

async_pluck(*column_names)

pluck相同,但非同步執行查詢並傳回ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 334
def async_pluck(*column_names)
  async.pluck(*column_names)
end

async_sum(identity_or_column = nil)

sum相同,但非同步執行查詢並傳回ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 182
def async_sum(identity_or_column = nil)
  async.sum(identity_or_column)
end

average(column_name)

計算給定欄位的平均值。如果沒有列,則傳回nil。有關帶有選項範例,請參閱calculate

Person.average(:age) # => 35.8
# File activerecord/lib/active_record/relation/calculations.rb, line 116
def average(column_name)
  calculate(:average, column_name)
end

calculate(operation, column_name)

這是計算給定欄位的總計值。countsumaverageminimummaximum的方法已新增為捷徑。

Person.calculate(:count, :all) # The same as Person.count
Person.average(:age) # SELECT AVG(age) FROM people...

# Selects the minimum age for any family without any minors
Person.group(:last_name).having("min(age) > 17").minimum(:age)

Person.sum("2 * age")

有兩種基本輸出格式

  • 單一總計值:對於COUNT,單一值強制轉換為整數;對於AVG,強制轉換為浮點數;對於其他所有值,強制轉換為給定欄位的類型。

  • 群組值:這會傳回一個有序雜湊,其中包含值並將這些值加以群組化。它可能是一個欄位名稱或屬於關聯的名稱。

    values = Person.group('last_name').maximum(:age)
    puts values["Drake"]
    # => 43
    
    drake  = Family.find_by(last_name: 'Drake')
    values = Person.group(:family).maximum(:age) # Person belongs_to :family
    puts values[drake]
    # => 43
    
    values.each do |family, max_age|
      ...
    end
    
# File activerecord/lib/active_record/relation/calculations.rb, line 217
def calculate(operation, column_name)
  operation = operation.to_s.downcase

  if @none
    case operation
    when "count", "sum"
      result = group_values.any? ? Hash.new : 0
      return @async ? Promise::Complete.new(result) : result
    when "average", "minimum", "maximum"
      result = group_values.any? ? Hash.new : nil
      return @async ? Promise::Complete.new(result) : result
    end
  end

  if has_include?(column_name)
    relation = apply_join_dependency

    if operation == "count"
      unless distinct_value || distinct_select?(column_name || select_for_count)
        relation.distinct!
        relation.select_values = Array(model.primary_key || table[Arel.star])
      end
      # PostgreSQL: ORDER BY expressions must appear in SELECT list when using DISTINCT
      relation.order_values = [] if group_values.empty?
    end

    relation.calculate(operation, column_name)
  else
    perform_calculation(operation, column_name)
  end
end

count(column_name = nil)

計算記錄數。

Person.count
# => the total count of all people

Person.count(:age)
# => returns the total count of all people whose age is present in database

Person.count(:all)
# => performs a COUNT(*) (:all is an alias for '*')

Person.distinct.count(:age)
# => counts the number of different age values

如果count關聯#group一起使用,它會傳回雜湊,其中其金鑰表示總計的欄位,而各自值則是很相對應的數量

Person.group(:city).count
# => { 'Rome' => 5, 'Paris' => 3 }

如果count關聯#group一起用於多個欄位,它會傳回雜湊,其中其金鑰是一個陣列,包含每個欄位的個別值,而每個金鑰的值會是count

Article.group(:status, :category).count
# =>  {["draft", "business"]=>10, ["draft", "technology"]=>4, ["published", "technology"]=>2}

如果count關聯#select一起使用,它會計算選取的欄位數

Person.select(:age).count
# => counts the number of different age values

注意:並非所有有效的關聯#select表示式都是有效count表示式。具體差異取決於資料庫。在無效情況下,會擲出資料庫的錯誤。

在提供區塊時,如果尚未載入關聯,則將載入關聯中所有的記錄。使用關聯中的每筆記錄呼叫區塊。傳回區塊傳回真值記錄數。

Person.count { |person| person.age > 21 }
# => counts the number of people older that 21

注意:如果關聯中有大量記錄,載入所有記錄可能會導致效能問題。

# File activerecord/lib/active_record/relation/calculations.rb, line 94
def count(column_name = nil)
  if block_given?
    unless column_name.nil?
      raise ArgumentError, "Column name argument is not supported when a block is passed."
    end

    super()
  else
    calculate(:count, column_name)
  end
end

ids()

使用表格的主鍵,傳回關聯的基礎模型 ID

Person.ids # SELECT people.id FROM people
Person.joins(:company).ids # SELECT people.id FROM people INNER JOIN companies ON companies.id = people.company_id
# File activerecord/lib/active_record/relation/calculations.rb, line 371
def ids
  primary_key_array = Array(primary_key)

  if loaded?
    result = records.map do |record|
      if primary_key_array.one?
        record._read_attribute(primary_key_array.first)
      else
        primary_key_array.map { |column| record._read_attribute(column) }
      end
    end
    return @async ? Promise::Complete.new(result) : result
  end

  if has_include?(primary_key)
    relation = apply_join_dependency.group(*primary_key_array)
    return relation.ids
  end

  columns = arel_columns(primary_key_array)
  relation = spawn
  relation.select_values = columns

  result = if relation.where_clause.contradiction?
    ActiveRecord::Result.empty
  else
    skip_query_cache_if_necessary do
      model.with_connection do |c|
        c.select_all(relation, "#{model.name} Ids", async: @async)
      end
    end
  end

  result.then { |result| type_cast_pluck_values(result, columns) }
end

maximum(欄位名稱)

計算特定欄位中的最大值。傳回的值與欄位的資料類型相同,如果沒有資料列,則傳回nil。請參閱 calculate,了解包含選項範例。

Person.maximum(:age) # => 93
# File activerecord/lib/active_record/relation/calculations.rb, line 146
def maximum(column_name)
  calculate(:maximum, column_name)
end

minimum(欄位名稱)

計算特定欄位中的最小值。傳回值與欄位的資料類型相同,如果沒有資料列,則傳回nil。請參閱 calculate,了解包含選項範例。

Person.minimum(:age) # => 7
# File activerecord/lib/active_record/relation/calculations.rb, line 131
def minimum(column_name)
  calculate(:minimum, column_name)
end

pick(*欄位名稱)

從當前關聯關係中挑選指定欄位的值。這是 relation.limit(1).pluck(*column_names).first 的簡寫形式,在將關聯關係縮小為單一資料列時,特別有用。

就像 pluck 一樣,pick 只會載入實際的值,而非整個紀錄物件,因此也比較有效率。與 pluck 一樣,值會依照欄位類型轉換類型。

Person.where(id: 1).pick(:name)
# SELECT people.name FROM people WHERE id = 1 LIMIT 1
# => 'David'

Person.where(id: 1).pick(:name, :email_address)
# SELECT people.name, people.email_address FROM people WHERE id = 1 LIMIT 1
# => [ 'David', 'david@loudthinking.com' ]
# File activerecord/lib/active_record/relation/calculations.rb, line 352
def pick(*column_names)
  if loaded? && all_attributes?(column_names)
    result = records.pick(*column_names)
    return @async ? Promise::Complete.new(result) : result
  end

  limit(1).pluck(*column_names).then(&:first)
end

pluck(*欄位名稱)

使用 pluck 作為捷徑,來選擇一個或多個屬性,而不會為每筆資料列載入整個紀錄物件。

Person.pluck(:name)

取代

Person.all.map(&:name)

pluck 傳回陣列 (Array),其屬性值已轉換類型,以符合所選欄位名稱(如果可以推斷的話)。預設情況下,所選 SQL 片段會傳回字串 (String) 值。

Person.pluck(:name)
# SELECT people.name FROM people
# => ['David', 'Jeremy', 'Jose']

Person.pluck(:id, :name)
# SELECT people.id, people.name FROM people
# => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]

Person.distinct.pluck(:role)
# SELECT DISTINCT role FROM people
# => ['admin', 'member', 'guest']

Person.where(age: 21).limit(5).pluck(:id)
# SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
# => [2, 3]

Comment.joins(:person).pluck(:id, person: :id)
# SELECT comments.id, person.id FROM comments INNER JOIN people person ON person.id = comments.person_id
# => [[1, 2], [2, 2]]

Comment.joins(:person).pluck(:id, person: [:id, :name])
# SELECT comments.id, person.id, person.name FROM comments INNER JOIN people person ON person.id = comments.person_id
# => [[1, 2, 'David'], [2, 2, 'David']]

Person.pluck(Arel.sql('DATEDIFF(updated_at, created_at)'))
# SELECT DATEDIFF(updated_at, created_at) FROM people
# => ['0', '27761', '173']

另請參閱 ids

# File activerecord/lib/active_record/relation/calculations.rb, line 291
def pluck(*column_names)
  if @none
    if @async
      return Promise::Complete.new([])
    else
      return []
    end
  end

  if loaded? && all_attributes?(column_names)
    result = records.pluck(*column_names)
    if @async
      return Promise::Complete.new(result)
    else
      return result
    end
  end

  if has_include?(column_names.first)
    relation = apply_join_dependency
    relation.pluck(*column_names)
  else
    model.disallow_raw_sql!(flattened_args(column_names))
    relation = spawn
    columns = relation.arel_columns(column_names)
    relation.select_values = columns
    result = skip_query_cache_if_necessary do
      if where_clause.contradiction?
        ActiveRecord::Result.empty(async: @async)
      else
        model.with_connection do |c|
          c.select_all(relation.arel, "#{model.name} Pluck", async: @async)
        end
      end
    end
    result.then do |result|
      type_cast_pluck_values(result, columns)
    end
  end
end

sum(初始值或欄位 = 0, &區塊)

計算特定欄位中的值總合。傳回的值與欄位的資料類型相同,如果沒有資料列,則傳回0。請參閱 calculate,了解包含選項範例。

Person.sum(:age) # => 4562

在提供區塊時,會載入關聯關係中的所有紀錄(如果關聯關係尚未載入的話)。在關聯關係中對每個紀錄呼叫區塊。傳回 initial_value_or_column 與區塊傳回值的總和

Person.sum { |person| person.age } # => 4562
Person.sum(1000) { |person| person.age } # => 5562

注意:如果關聯中有大量記錄,載入所有記錄可能會導致效能問題。

# File activerecord/lib/active_record/relation/calculations.rb, line 172
def sum(initial_value_or_column = 0, &block)
  if block_given?
    map(&block).sum(initial_value_or_column)
  else
    calculate(:sum, initial_value_or_column)
  end
end