As explained by K M Rakibul Islam
, your problem is that you're calling .count
on an undefined variable (@course.attendees
).
--
The fix - according to this answer: ActiveRecord: size vs count - could be to use size
instead of count
:
@count_attendance = @course.attendees.size
If this still returns the same error, you'll want to use some conditional code to make sure you're only calling methods on attendees
if any exist:
def update
@course = Course.find params[:id]
@course.update attendance: @count.attendees.size if @count.attendees.any?
end
counter_cache
A much better solution to this is the counter_cache
functionality of Rails:
#app/models/attendee.rb
class Attendee < ActiveRecord::Base
belongs_to :course, counter_cache: :attendance
end
#app/models/course.rb
class Course < ActiveRecord::Base
has_many :attendees
end
From the docs:
The :counter_cache
option can be used to make finding the number of belonging objects more efficient...
With these declarations, asking for the value of @customer.orders.size
requires making a call to the database to perform a COUNT(*)
query. To avoid this call, you can add a counter cache to the belonging model
--
The reason your functionality works in development, but not production, is that your development db
will likely have attendees
populated with the relevant data. Heroku uses a separate database, meaning that you have to accomodate for any nil
responses.