2009-10-07 47 views
0

考慮到這一點:知道父母從物體

@article = Article.first(:joins => :category) 

是否ActiveRecord的提供了返回的任何一個陣列屬於類別名稱的generique方法?

例如:

@article.name.parents # => ["category"] 

感謝

回答

0

要找到適合您的機型所有的「belongs_to的」協會,那些都是「父母」,你可以這樣做:

YourModel.reflections.select { |name, reflection| reflection.macro == :belongs_to } 
+0

好主意!非常感謝。我只是添加一些其他的方法,沒關係:Article.reflections.select {| name,reflection | reflection.macro ==:belongs_to} .collect {| table |表[0] .to_s.classify} – Denis 2009-10-08 09:33:32

0

當你有兩個模型之間的關係,例如,具有一類的文章,你就必須在類別的has_many關係。並在文章中的belongs_to。

class Article < ActiveRecord::Base 
    belongs_to :category 
end 

class Category < ActiveRecord::Base 
    has_many :articles 
end 

然後,您可以從文章或類別中檢索相關對象。

article.category # => The category 
category.articles # => The articles 

沒有「父母」。每個模型都有自己的關係。如果您需要檢索一個模型的關係,則必須對其進行定義才能訪問它。

+0

謝謝您的回答。 A同意你的觀點。但我想用一個通用的方法來做到這一點。如果文章屬於類別和雜誌,我想提供: @ article.name.parents#=> [「Category」,「Magazine」] 但Article.parents方法不會返回每個belongs_to類,並在測試了一些其他方法後,如: @ article.belongs_to 我得到一個錯誤(因爲belongs_to需要一個參數)或其他信息。並通過嘗試以下搜索後: @ article.class.methods.each {| method |開始@ article.class.send(方法)救援真正結束} 我得到一個錯誤。 – Denis 2009-10-07 20:46:39

0

我相信這是不可能的,導致Rails在某些類中有belongs_to :something時正在做的事情,是一種元編程技術,在該類內部添加方法def something並且它並不真正存儲這些「父」類。

相關問題