0

因此,我的评论下方有一个带有“赞”按钮的页面,并且正在尝试解决如何在不刷新整个页面的情况下执行此操作,当前代码如下所示:

- if can? :like, comment
  = " · "
  - if likes.find_by_user_id(current_user.id).nil?
    = link_to "Like", like_comment_path(comment), method: :post
  - else
    = link_to "Unlike", unlike_comment_path(comment), method: :post
- if comment.user == current_user
  = " · "
  = link_to "Delete", comment_path(comment), method: :delete,
    :data => { :confirm => "Are you sure you want to delete this comment?" }
- if likes.count > 0
.comment-likes
  - likers = likes.map { |like| link_to(like.user_name, "#") }
  - if likers.length > 1
    - likers = likers.slice(0, likers.length - 1).join(", ").concat(" and " +                               likers.slice(-1))
  - else
    - likers = likers[0]
  = "Liked by #{likers}".html_safe

将like和like的方法更改为:post到:update似乎有很大的不同,这个函数使用ajax和:post不是吗?如果不是,那么我将如何将它变成一个 ajax 函数。

这是我的comments_controller.rb 东西

def like
 comment_vote = resource.like current_user
 Event.comment_liked!(comment_vote)
 redirect_to discussion_url(resource.discussion)
end

def unlike
 resource.unlike current_user
 redirect_to discussion_url(resource.discussion)
end
4

1 回答 1

3

= link_to "Like", like_comment_path(comment), method: :post, remote: true

然后在你的 likes_controller 创建动作,respond_to format.js

def create
  respond_to do |format|
    format.html { .. your liking code .. }
    format.js {.. your liking code .. }
  end
end

然后,这将调用您的视图文件夹中的 create.js.erb,您可以从那里动态更新您的 html

于 2012-09-17T07:21:20.290 回答