2

我(想要)在父模型(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

目前它不起作用,因为它正在返回false所有东西 - 无论是否subjectgoals。任何想法如何让这个工作?

4

1 回答 1

4

检查是否有任何subjects至少有一个goal(如果主题没有目标,subjects.goals应该返回):[]

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

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

于 2013-08-20T15:38:00.590 回答