2013-04-03 23 views
1

我想爲模型(在這種情況下爲參與者模型)編寫一個方法,查看它的某些關聯集合,並簡單地說明是否存在關聯關係。以下是我有:查詢模型實例是否有任何指定的關聯集合

def post_screener_associations? 
    ParticipantAuthorizationForm.where(:participant_id => self.id).count > 0 
    ParticipantConsent.where(:participant_id => self.id).count > 0 
    # and so on exactly like the format above about 8 more times! 
    end 

我知道有一種更好的方式來寫這個查詢,但我不希望錯誤我的同事。謝謝。

回答

0
def post_screener_associations? 
    self.class.reflect_on_all_associations.all? { |a| send(a.name).present? } 
    end 

這應該要求每個協會是它存在,並且如果所有在場的方法將返回true,以另一種方式會是假的

0

的情況下,另一種選擇,你不想使用反射。它與您的原始文章相似,使用您在參與者模型中的活動記錄方法來簡化它。

def post_screeener_associations? 
    participant_authorization_form.present? || 
    participant_consent.present? || 
    # etc. 
end 
+0

謝謝。這是我真正想要的。我知道有一個更清晰的方法來獲得結果。 –

相關問題