0

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?

dewyze
  • 979
  • 1
  • 7
  • 21
  • did you solve it? I'm encountering a different yet similar problem... – Boaz Dec 23 '13 at 22:28
  • I ended up just figuring out how many to delete in the controller and creating an @number variable. That way if I am deleting one or deleting all I just call `if current_user.deliveries_count - @number == 0`. I don't know if it's cleanest, but it works just fine. – dewyze Dec 28 '13 at 02:28
  • I got an answer eventually in my question. FYI for the next time http://stackoverflow.com/questions/20747832/counter-cache-not-updated-in-ajax/20771646?noredirect=1#comment31133170_20771646 – Boaz Dec 29 '13 at 08:34

0 Answers0