2011-09-01 84 views
2

我有很多動態的代碼保持複雜的關係在一個字符串中。 例如:Rails如何查詢關聯定義

"product.country.continent.planet.galaxy.name" 

我如何檢查是否存在這些關係? 我想要一個類似如下的方法:

raise "n00b" unless Product.has_associations?("product.country.planet.galaxy") 

我該如何實現這個?

+0

我想我們需要更多的代碼在這裏,你在字符串中存儲了什麼樣的關聯?活躍的記錄協會? – Jimmy

回答

2

試試這個:

def has_associations?(assoc_str) 
    klass = self.class 
    assoc_str.split(".").all? do |name| 
    (klass = klass.reflect_on_association(name.to_sym).try(:klass)).present? 
    end 
end 
+0

剛剛通過reflect_on_association(name.to_sym)替換reflect_on_association(name)並像魅力一樣工作! –

0

如果這些活動記錄協會,這裏是你如何能做到這一點:

current_class = Product 
has_associations = true 
paths = "country.planet.galaxy".split('.') 

paths.each |item| 
    association = current_class.reflect_on_association(item) 
    if association 
    current_class = association.klass 
    else 
    has_associations = false 
    end 
end 

puts has_association 

,這將告訴你,如果這個特定的路徑具有的所有關聯。

0

如果確實要將AR關聯存儲爲類似的字符串,則放置在初始化程序中的此代碼應該允許您執行所需的操作。對於我的生活,我無法弄清楚爲什麼你想這樣做,但我相信你有你的理由。

class ActiveRecord::Base 
    def self.has_associations?(relation_string="") 
    klass = self 
    relation_string.split('.').each { |j| 
     # check to see if this is an association for this model 
     # and if so, save it so that we can get the class_name of 
     # the associated model to repeat this step 
     if assoc = klass.reflect_on_association(j.to_sym) 
     klass = Kernel.const_get(assoc.class_name) 
     # alternatively, check if this is a method on the model (e.g.: "name") 
     elsif klass.instance_method_already_implemented?(j) 
     true 
     else 
     raise "Association/Method #{klass.to_s}##{j} does not exist" 
     end 
    } 
    return true 
    end 
end 

有了這個,你就需要離開過最初的型號名稱,所以你的例子那就是:

Product.has_associations?("country.planet.galaxy")