2010-01-07 65 views
29

有沒有辦法找出模型具有哪些關聯?把這些2種型號:rails方法獲取模型的關聯名稱

class Comment < ActiveRecord::Base 
    belongs_to :commentable 
end 

class Post < ActiveRecord::Base 
    has_many :comments 
    belongs_to :user 
end 

我在尋找類似:

Post.has_many #=> ['comments', ...] 
Post.belongs_to # => ['user'] 
Comment.belongs_to # => ['commentable'] 

回答

65

您正在尋找reflect_on_all_associations

因此,在短期:

Post.reflect_on_all_associations(:has_many) 

...將給予(與像name屬性等對象的)所有has_many協會的數組。

+1

完美!謝謝。 – DiegoSalazar 2010-01-09 19:18:10