Reputation: 8451
I can't seem to understand why I get this error message when I try to call count on my method? Here is my code
<div class="container">
<h2>Statistics</h2>
<hr />
<h3 class="total-number">Total Signups: <%= @engaged %></h3>
<h3 class='total-number'> All Subscribed People: <%= @person %></h3>
<hr />
<p class='total-number'> Visitor group: <%= @visitor.people.count %></p>
<p class='total-number'> Dance group: <%= @dance.people.count %></p>
<p class='total-number'> Staff group: <%= @staff.people.count %></p>
<p class='total-number'> Volunteer group: <%= @volunteer.people.count %></p>
<hr />
<p><%= link_to "Send Message", root_path %></p>
</div>
Here is my controller
def subscribed_num
@person = Person.subscribed.count
@engaged = Person.count
@dance = Group.find_by(name: "dance")
@visitor = Group.find_by(name: "visitor")
@volunteer = Group.find_by(name: "volunteer")
@staff = Group.find_by(name: "staff")
end
It seems straight forward but I'm probably doing something small wrong.
Upvotes: 1
Views: 120
Reputation: 4555
Group.find_by(name: 'something')
will return nil
if there's no Group matching the name.
So one of visitor, dance, staff or volunteer seems to not exist.
One way to handle such situations is to use a Null Object to represent the absence of a group.
A null group could always have an empty array of people.
Here's an example using the excellent Naught gem written by Avdi Grimm:
NullGroup = Naught.build do |builder|
def people
[]
end
end
# controller
def subscribed_num
@person = Person.subscribed.count
@engaged = Person.count
@dance = Group.find_by(name: "dance") || NullGroup.new
@visitor = Group.find_by(name: "visitor") || NullGroup.new
@volunteer = Group.find_by(name: "volunteer") || NullGroup.new
@staff = Group.find_by(name: "staff") || NullGroup.new
end
#
Upvotes: 3