跳至内容 跳至搜索

Active Record Reflection

Reflection 能够检查 Active Record 类和对象的关联和聚合。例如,此信息可用于表单生成器中,该生成器采用 Active Record 对象并根据其类型创建所有属性的输入字段,并显示与其他对象的关联。

MacroReflection 类具有 AggregateReflection 和 AssociationReflection 类的信息。

方法
R

实例公共方法

reflect_on_aggregation(aggregation)

返回命名aggregation(使用符号)的 AggregateReflection 对象。

Account.reflect_on_aggregation(:balance) # => the balance AggregateReflection
# File activerecord/lib/active_record/reflection.rb, line 69
def reflect_on_aggregation(aggregation)
  aggregate_reflections[aggregation.to_s]
end

reflect_on_all_aggregations()

返回类中所有聚合的 AggregateReflection 对象数组。

# File activerecord/lib/active_record/reflection.rb, line 61
def reflect_on_all_aggregations
  aggregate_reflections.values
end

reflect_on_all_associations(macro = nil)

返回类中所有关联的 AssociationReflection 对象数组。如果您只想反映特定关联类型,请将符号(:has_many:has_one:belongs_to)作为第一个参数传入。

示例

Account.reflect_on_all_associations             # returns an array of all associations
Account.reflect_on_all_associations(:has_many)  # returns an array of all has_many associations
# File activerecord/lib/active_record/reflection.rb, line 106
def reflect_on_all_associations(macro = nil)
  association_reflections = reflections.values
  association_reflections.select! { |reflection| reflection.macro == macro } if macro
  association_reflections
end

reflect_on_all_autosave_associations()

返回启用了 :autosave 的所有关联的 AssociationReflection 对象数组。

# File activerecord/lib/active_record/reflection.rb, line 126
def reflect_on_all_autosave_associations
  reflections.values.select { |reflection| reflection.options[:autosave] }
end

reflect_on_association(association)

返回 association(使用符号)的 AssociationReflection 对象。

Account.reflect_on_association(:owner)             # returns the owner AssociationReflection
Invoice.reflect_on_association(:line_items).macro  # returns :has_many
# File activerecord/lib/active_record/reflection.rb, line 117
def reflect_on_association(association)
  reflections[association.to_s]
end

reflections()

返回一个 Hash,其中反射的名称作为键,AssociationReflection 作为值。

Account.reflections # => {"balance" => AggregateReflection}
# File activerecord/lib/active_record/reflection.rb, line 77
def reflections
  @__reflections ||= begin
    ref = {}

    _reflections.each do |name, reflection|
      parent_reflection = reflection.parent_reflection

      if parent_reflection
        parent_name = parent_reflection.name
        ref[parent_name.to_s] = parent_reflection
      else
        ref[name] = reflection
      end
    end

    ref
  end
end