跳到內容 跳到搜尋

Active Record 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()

傳回啟用 :autosave 的所有關聯的 AssociationReflection 物件陣列。

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

傳回一個以反思的名稱作為鍵,並以 AssociationReflection 作為值的 Hash

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