跳至内容 跳至搜索

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 413
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_pick(*column_names)

pick相同,但以异步方式执行查询并返回ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 367
def async_pick(*column_names)
  async.pick(*column_names)
end

async_pluck(*column_names)

pluck相同,但以异步方式执行查询并返回ActiveRecord::Promise

# File activerecord/lib/active_record/relation/calculations.rb, line 338
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 181
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,单个值会被类型转换为Integer;对于 AVG,会被转换为Float;对于其他所有情况,则会转换为给定列的类型。

  • 分组值:这将返回一个有序哈希,包含值并按组进行分组。它接受列名或belongs_to关联的名称。

    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 216
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

如果countRelation#group一起使用,则返回一个Hash,其键表示聚合的列,值是相应的数量

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

如果countRelation#group一起用于多个列,则返回一个Hash,其键是一个包含每列单个值的数组,每个键的值是计数。

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

如果countRelation#select一起使用,它将计算选定的列

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

注意:并非所有有效的Relation#select表达式都有效count表达式。具体细节因数据库而异。在无效的情况下,会抛出数据库错误。

当给出块时,将使用关系中的每个记录调用该块,并返回块返回真值(truthy value)的记录数。

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

如果关系尚未加载,调用带块的count将加载关系中的所有记录。如果关系中的记录很多,加载所有记录可能会导致性能问题。

# 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 375
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(column_name)

计算给定列的最大值。返回的值具有与列相同的数据类型,如果没有行则为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(column_name)

计算给定列的最小值。返回的值具有与列相同的数据类型,如果没有行则为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(*column_names)

从当前关系中的命名列中选取值。这是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 356
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(*column_names)

使用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']

请注意,pluck会忽略任何之前的 select 子句。

Person.select(:name).pluck(:id)
# SELECT people.id FROM people

另请参阅ids

# File activerecord/lib/active_record/relation/calculations.rb, line 295
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? && !possible_aggregation?(column_names)
        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(initial_value_or_column = 0, &block)

计算给定列的值的总和。返回的值具有与列相同的数据类型,如果没有行则为0。有关带选项的示例,请参阅calculate

Person.sum(:age) # => 4562

当给定块时,将使用关系中的每个记录调用该块,并返回initial_value_or_column加上块返回值之和

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

如果关系尚未加载,调用带块的sum将加载关系中的所有记录。如果关系中的记录很多,加载所有记录可能会导致性能问题。

# File activerecord/lib/active_record/relation/calculations.rb, line 171
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

实例保护方法

aggregate_column(column_name)

# File activerecord/lib/active_record/relation/calculations.rb, line 418
def aggregate_column(column_name)
  case column_name
  when Arel::Expressions
    column_name
  when :all
    Arel.star
  else
    arel_column(column_name.to_s)
  end
end