Kobius
Kobius

Reputation: 714

Rails - Ajax with Partial increasing counter_cache by 2 instead of 1

On a movie page, such as "/batman" there is a button labelled "Seen This". On click, it increases the seens_count by 1.

In the rails console, I can see it only increases by one - but my JS partial increases by 2. If I refresh the page after clicking the button, it goes back to just 1.

Why does it show 2 instead of 1? When the actual value of seens_count is 1.

/movies/show.html.erb:

<div id="count-seens">
  <%= @movie.seens_count %> (Shows 2 after clicking Ajax button, should show 1)
  <%= @movie.seens.count %> (Correctly shows 1 after clicking Ajax button)
</div>

<%= link_to "I've Seen This", movie_create_seen_path(movie), method: :post, remote: true, class: "button" %>

/movies/seens/create.js.erb

$("#count-seens").html("<%= j render partial: 'movies/count_seens', locals: { movie: @movie } %>");

seens_controller.rb:

def create
  @movie.seens.where(user_id: current_user.id).first_or_create

  respond_to do |format|
    format.html { redirect_to @movie }
    format.js
  end
end

seen.rb:

belongs_to :movie, counter_cache: true

I also have some validations in place for specific movies. For these movies, users cannot "Seen" - however for these pages, the counter_cache increases by 1. When I refresh the page, it goes back to 0 - as it should be. Either way, it seems that every counter cache has a ghost "+1".

Upvotes: 0

Views: 120

Answers (1)

asimhashmi
asimhashmi

Reputation: 4378

Counts showing incorrect values, when using counter cache is a known issue in Rails 4.1.14.1, 4.2.5.1, 5.0.0.beta2.

One option may be to explicitly define a custom column instead of using the default one.

Maybe something like this:

belongs_to :movie, counter_cache: :movie_seen_count

Also see the discussion related to this issue here

Upvotes: 1

Related Questions