Ajax中未更新counter_cache [英] counter_cache not updated in ajax

查看:53
本文介绍了Ajax中未更新counter_cache的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个运行的js代码,单击了一个喜欢的链接(使用ajax)-链接更改为不相同(使用正确的路线和方法),并且我希望对likes_count(该模型中的列)进行更新也是

I have a js code that is run a like link is clicked (with ajax) - The link changes to unlike (with the proper route and method), and I want the likes_count which is a column in the model to be updated as well.

问题是该值不会更新.没有Ajax(整页加载)时-值确定

The thing is that the value doesn't get updated. With no Ajax (full page load) - the value is OK

#create.js.erb
$("#like_link").html("<%= escape_javascript(render("artworks/unlike")) %>")
$("#likes").html('<%= @artwork.likes_count %>')

#relevant html snippet from the view
<div>
  Total likes: <span id="likes"><%= @artwork.likes_count %></span>  
</div>

#model - like.rb
class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :artwork, :counter_cache => true
end

使用时
$(#likes").html('<%= @ artwork.count%>')
它有效,但是缺少counter_cache的要点

When using
$("#likes").html('<%= @artwork.count %>')
It works but missing the point of counter_cache

推荐答案

在您的create方法中,恰好在保存对象之后,您应该 reload 您喜欢的对象,如下所示:

in your create method, exactly after saving your object, you should reload the object that you like it, something like this :

def create
    # some code
    if @like.save
        @artwork.reload # use reload to get the updated counter cache value
    end
end

这篇关于Ajax中未更新counter_cache的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆