Rails:如何测试父母是否有孙子孙女出现在儿童模型中

时间:2013-08-20 15:24:34

标签: ruby-on-rails ruby-on-rails-3 methods

我(想)在父模型(groups)中有一个方法来检查孩子(subjects)是否有孩子(goals

groups.rb

def has_goals?
  @answer = []
  subjects = self.subjects
  subjects.each do |subject|
    if subject.try(:goals).present?
      @answer << true
    else
      @answer << false
    end  
  end  
  if @answer.include?("true")
    true
  else
    false
  end
end

我会这样使用 -

if group.has_goals?
  # do something
else
  # do something else
end

目前它不起作用,因为它正在为{1}}返回false - subject是否有goals。任何想法如何使这个工作?

1 个答案:

答案 0 :(得分:4)

如果主题没有目标,请检查subjects是否至少有goal subjects.goals应该返回[]

def has_goals
  subjects.any? { |subject| subject.goals.present? }
end

可枚举#任何?参考:http://ruby-doc.org/core-2.0/Enumerable.html#method-i-any-3F