I have a page where a User can see their deliveries (like a notification). On that page they could delete a single delivery by clicking on an X. That was linked with the following controller actions
deliveries_controller.rb
def destroy
@id = params[:id]
@delivery = Delivery.find(@id)
@delivery.destroy
respond_to do |format|
format.js
end
end
This called the following js file called via AJAX:
destroy.js.erb
<% if @id %>
$("#delivery<%= @id %>").hide('fast');
<% end %>
<% if current_user.deliveries_count == 0 %> # Used to be current_user.deliveries.empty?
$(".delete, .close").hide('fast');
setTimeout(function() {
$("#message").fadeIn('slow');}
,300);
<% end %>
When the deliveries line was current_user.deliveries.empty? and there was no counter cache, this would work fine. If the last delivery was deleted, it would show the empty message. However, when I added a counter cache (I kept making empty? calls, wanted to try and avoid the database hit) this code no longer worked. I tried empty? and deliveries_count and deliveries.size and several other things.
I don't even need to change this code, but if I add a deliveries counter_cache this fails. The JS file sees that the deliveries count is still 1 higher than it should be. Does anyone know why?