我(想)在父模型(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
。任何想法如何使这个工作?
答案 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