【问题标题】:Rails - Ajax with Partial increasing counter_cache by 2 instead of 1Rails - Ajax 部分将 counter_cache 增加 2 而不是 1
【发布时间】:2020-05-15 15:07:27
【问题描述】:

在电影页面上,例如“/batman”,有一个标记为“Seen This”的按钮。点击时,seens_count 增加 1。

在 Rails 控制台中,我可以看到它只增加了 1 - 但我的 JS 部分增加了 2。如果我在单击按钮后刷新页面,它会返回到 1。

为什么显示的是 2 而不是 1?当 seens_count 的实际值为 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

我还对特定电影进行了一些验证。对于这些电影,用户无法“看到” - 但是对于这些页面,counter_cache 增加 1。当我刷新页面时,它会回到 0 - 应该是这样。无论哪种方式,似乎每个计数器缓存都有一个幽灵“+1”。

【问题讨论】:

  • ajax 调用在哪里?
  • 您使用的 Rails 的确切版本是什么?还可以尝试在调用first_or_create 时记录这些计数器。您是否尝试在控制台中重复该确切调用?我认为你的回调/验证中有一些东西会触发这个,而不是 ajax

标签: jquery ruby-on-rails ruby ajax


【解决方案1】:

使用计数器缓存时计数显示不正确的值是 Rails 4.1.14.14.2.5.15.0.0.beta2 中的一个已知问题。

一种选择可能是显式定义自定义列而不是使用默认列。

可能是这样的:

belongs_to :movie, counter_cache: :movie_seen_count

另见与此问题相关的讨论here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多