跳至内容 跳至搜索

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 70
def reflect_on_aggregation(aggregation)
  aggregate_reflections[aggregation.to_sym]
end

reflect_on_all_aggregations()

返回一个 AggregateReflection 对象数组,这些对象代表类中所有聚合。

# File activerecord/lib/active_record/reflection.rb, line 62
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 111
def reflect_on_all_associations(macro = nil)
  association_reflections = normalized_reflections.values
  association_reflections.select! { |reflection| reflection.macro == macro } if macro
  association_reflections
end

reflect_on_all_autosave_associations()

返回一个 AssociationReflection 对象数组,这些对象代表所有启用了 :autosave 的关联。

# File activerecord/lib/active_record/reflection.rb, line 131
def reflect_on_all_autosave_associations
  reflections = normalized_reflections.values
  reflections.select! { |reflection| reflection.options[:autosave] }
  reflections
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 122
def reflect_on_association(association)
  normalized_reflections[association.to_sym]
end

reflections()

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

Account.reflections # => {"balance" => AggregateReflection}
# File activerecord/lib/active_record/reflection.rb, line 78
def reflections
  normalized_reflections.stringify_keys
end