8

実行時に ActiveRecord クラスの関連付けを見つけたいのですが...

私が次のものを持っているとしましょう:

class Person < ActiveRecord::Base
  has_many :chairs
  has_many :pens
end

class Chair < ActiveRecord::Base
  belongs_to :person
end

class Pen < ActiveRecord::Base
  belongs_to :person
end

Person が "多くの" 椅子とペンを持っていること、およびその逆を実行時に確認するにはどうすればよいですか? 文字列の配列を返すメソッドを探しています (そのようなメソッドが存在する場合)。すなわち

Person.has_many_assocations 

戻ります:

["chairs", "pens"] 

Pen.belongs_to_associations

戻ります:

["person"]

存在するこのようなメソッドがありませんか??

ご協力いただきありがとうございます。

4

2 に答える 2

26

ActiveRecord::Reflectionクラスが探しているものかもしれません。ドキュメントから:

  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
于 2009-03-13T21:49:33.933 に答える
0

実行時に行うのはかなりばかげているように思えます。正確に何を達成しようとしていますか?あなたの問題が何であれ、単純でより一般的に使用される解決策があると思います。

必要に応じて、を使用しますTheModel.read_inheritable_attribute(:reflections)

于 2009-03-13T22:07:11.380 に答える