Reputation: 10997
I (want to) have a method in a parent model (groups
) to check if a child (subjects
) has children (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
I would use this like so -
if group.has_goals?
# do something
else
# do something else
end
at the moment it's not working as it's returning false
for everything - whether the subject
has goals
or not. Any ideas how to get this working?
Upvotes: 2
Views: 706
Reputation: 4232
Check if any of the subjects
has at least a goal
(subjects.goals
should return []
if the subject has no goals):
def has_goals
subjects.any? { |subject| subject.goals.present? }
end
Enumerable#any? reference: http://ruby-doc.org/core-2.0/Enumerable.html#method-i-any-3F
Upvotes: 4