Rails 4中的Ajax不更新内容

时间:2015-09-24 14:19:37

标签: jquery ruby-on-rails ajax

我有控制器:"喜欢"行动:"创建"

def create
 @micropost = Micropost.find(params[:micropost_id])
 current_user.like(@micropost)
 @micropost.reload

 @likes = @micropost.count_likes

 respond_to do |format|
   format.html { redirect_to root_path }
   format.js
 end
end

此操作将请求json并使用ajax更新视图,如果我写的话,视图将正确呈现:

$("#like_count-<%= @micropost.id %>").html('<%= @likes %>');

但写作:

$("#like_count-<%= @micropost.id %>").html('<%= @micropost.count_likes %>');

没有效果。我还检查过@ micropost.reload之后,@ micropost.count_likes的值已经更新。我不知道发生这种情况的原因。希望你们能提供帮助。以下是Micropost的源代码:

class Micropost < ActiveRecord::Base
 # micropost belong to one user
 belongs_to :user

 # many user can like one micropost
 has_many :user_likes, class_name: "Like",
       foreign_key: "micropost_id",
       dependent: :destroy
 has_many :likers, through: :user_likes, source: :user

 default_scope -> { order(created_at: :desc) }
 mount_uploader :picture, PictureUploader

 validates(:content, presence: true, length: {:maximum => 200})
 validates(:user_id, presence: true)
 validate :picture_size

 def count_likes
   user_likes.length > 0 ? "(#{user_likes.length})" : ""
 end

 private
 # Validates the size of an uploaded picture.
 def picture_size
   if picture.size > 1.megabytes
     errors.add(:picture, "should be less than 1MB")
  end
 end
end

更新

对Likes#create:

的表单发布请求
<%= form_for(micropost.user_likes.build, remote: true) do |f| %>
<div><%= hidden_field_tag :micropost_id, micropost.id %></div>
<%= f.submit "like", class: "btn btn-primary", style: "width: 100px" %>
<% end %>

用户类:

class User < ActiveRecord::Base
...
# user can like many microposts
has_many :pos_likes, class_name: "Like",
       foreign_key: "user_id",
       dependent: :destroy
has_many :fav_posts, through: :pos_likes, source: :micropost
...
# like a post
def like(micropost)
   self.pos_likes.create(user_id: self.id, micropost_id: micropost.id)
end

1 个答案:

答案 0 :(得分:0)

此处的问题是使用#length而不是#count方法。 下面是对它们之间差异的一个很好的解释:

Difference between size, length and count in complicated ActiveRecord case

要解决此问题,您需要在user_likes.count

使用user_likes.length代替Micropost#count_likes