查询模型实例是否具有任何指定的关联集

时间:2013-04-03 17:44:38

标签: ruby-on-rails associations

我想为模型(在这种情况下,参与者模型)编写一个方法,该方法查看某组关联,并简单地说明是否存在。这就是我所拥有的:

  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

我知道有更好的方法来编写这个查询,但我不想让我的同事搞错。感谢。

2 个答案:

答案 0 :(得分:0)

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

这应该询问每个关联是否存在以及所有现有方法是否将返回true,否则它将是错误的

答案 1 :(得分:0)

另一种选择,以防您不想使用反射。它与原始帖子类似,使用参与者模型上的活动记录方法简化它。

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