HasManyReflection & HasOneReflection & BelongsToReflection & HasAndBelongsToManyReflection RuntimeReflection
| |
V V
AggregateReflection & AssociationReflection PolymorphicReflection
| |
V V
MacroReflection & ThroughReflection
|
V
AbstractReflection
一般关联和 aggregate 要区分开来。前者用 _reflections,后者用 aggregate_reflections.
create
add_reflection
add_aggregate_reflection
reflections # 所有正常的关联
reflect_on_all_associations # 指定 macro 的 reflections
reflect_on_all_autosave_associations # 包含 autosave: true 的 reflections
reflect_on_all_aggregations # 所有 aggregate 关联
# 以下两方法要提供被关联对象名字
reflect_on_association
reflect_on_aggregation
User.reflections.keys
=> [:comments,
:warehouse]
User.reflections.each_pair { |a, x| puts [a, x.macro].join(' => ') };
=> comments => has_many
warehouse => belongs_to
User.reflections.values.first.class
=> ActiveRecord::Reflection::AssociationReflection
r = User.reflections[:warehouse]
=> #<ActiveRecord::Reflection::AssociationReflection:0x007ff4606c66d0
@active_record=
User(id: integer, login: string, email: string, warehouse_id: integer),
@class_name="Warehouse",
@collection=false,
@klass=
Warehouse(id: integer, name: string),
@macro=:belongs_to,
@name=:warehouse,
@options={},
@plural_name="warehouses",
@quoted_table_name="`warehouses`",
@table_name="warehouses">
r.active_record
=> User(id: integer, login: string, email: string, warehouse_id: integer)
Post.reflections[:comments].table_name # => "comments"
Post.reflections[:comments].macro # => :has_many
Post.reflections[:comments].primary_key_name # => "message_id"
Post.reflections[:comments].foreign_key # => "message_id"