2011-08-10 72 views
1

我只想刪除資源,如果它們實際上屬於該對象。例如:在rails中是否有has_association?('association_name')方法

Post.all.each do |post| 
    if post.has_method?('name') 
     true 
    else 
     false 
    end 
end 

但檢查關聯:

Post.all.each do |post| 
    if post.has_many?('tags') 
     true 
    else 
     false 
    end 
end 

或:

Post.all.each do |post| 
    if post.belongs_to?('category') 
     true 
    else 
     false 
    end 
end 

回答

3

你可以編寫你自己的方法:

def has_many?(association) 
    self.class.reflect_on_all_associations(:has_many).any?{|a| a.name == association} 
end 

def belongs_to?(association) 
    self.class.reflect_on_all_associations(:belongs_to).any?{|a| a.name == association} 
end 

所以

Post.all.each do |post| 
    post.has_many?('tags') ? "yeap" : "nope" 
    post.belongs_to?('category') ? "yeap" : "nope" 
end 

或者你可以用簡單的結構:

Post.all.each do |post| 
    post.methods.include?('tags') ? true :false 
    post.methods.include?('category') ? true :false 
    post.methods.include?('name') ? true :false 
end 

UPD

或者,正如你正確地指出,你可以使用respond_to?

post.respond_to? :comments 
+0

喲,這個'.respond_to?(:tag)' – s84

+0

@Codeglot,'respond_to?'怎麼樣?將適合你的需要完美,以及。它是相同的'方法。包括?'但更短 – fl00r

1

也許像(用Rails 3)?:

if Post.categories.exists? # Rails 2 syntax would be Post.categories.present? (I think) 
    true 
else 
    false 
end 
+0

如果沒有任何'categories'方法,'Post.categories.exists?'會拋出錯誤 – fl00r

+0

感謝您的幫助。我實際上在一個rails 2.x應用程序:( – s84

相關問題