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
reflect_on_all_aggregations() 链接
返回类中所有聚合的 AggregateReflection 对象数组。
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
源代码: 显示 | 在 GitHub 上
# 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 对象数组。
源代码: 显示 | 在 GitHub 上
# 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
源代码: 显示 | 在 GitHub 上
# 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}
源代码: 显示 | 在 GitHub 上
# 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