所以我遇到的问题是让我的喜欢/不喜欢按钮在我的 Ruby on Rails 应用程序中使用 ajax 刷新,这是我的代码:
应用程序/视图/_comment.html.haml
- likes = comment.likes
%div.comment{id: "comment-#{comment.id}"}
.comment-avatar
.medium-user-avatar.avatar-canvas
- if comment.user.avatar_url
= image_tag comment.user.avatar_url(:medium)
- else
%span.medium-user-initials.initials-decoration
= comment.user.avatar_initials
%span.comment-username= link_to(comment.user_name, "#")
%span.comment-body~ markdown(comment.body)
.comment-time
= time_ago_in_words(comment.created_at) + " ago"
- if can? :like, comment
= " · "
- if likes.find_by_user_id(current_user.id).nil?
= link_to "Like", like_comment_path(comment), method: :post, remote: true
- else
= link_to "Unlike", unlike_comment_path(comment), method: :post, remote: true
- if comment.user == current_user
= " · "
= link_to "Delete", comment_path(comment), method: :delete, remote: true,
: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
应用程序/控制器/comments_controller.rb
class CommentsController < BaseController
load_and_authorize_resource
def destroy
destroy!{ discussion_url(resource.discussion ) }
end
def like
comment_vote = resource.like current_user
Event.comment_liked!(comment_vote)
#redirect_to discussion_url(resource.discussion )
render :partial => "like"
comment_likes
end
def unlike
resource.unlike current_user
#redirect_to discussion_url(resource.discussion)
render :partial => "unlike"
comment_likes
end
def comment_likes
render :partial => "comment_likes"
end
end
然后是 like、like 和 comment_likes 的 .js.erb 文件:
应用程序/视图/_like.js.erb
$(".comment-time a#like").html("<%= escape_javascript(render('.comment-time a#like'")
应用程序/视图/_unlike.js.erb
$(".comment-time a#unlike").html("<%= escape_javascript(render('.comment-time a#unlike'")
app/views/_comment_likes.js.erb
$(".comment-likes a##").html("<%= escape_javascript(render('.comment-likes a##'")
目前单击like 将更新数据库,但在页面刷新之前不会显示更改,我只想用ajax 刷新单个div。有关 div 的更多信息可能会有所帮助,因此 ruby 创建 html 并包含在其中作为示例,或者当已经喜欢时,我只需要刷新这些 div 以显示数据库中的最新信息以及包含 http://localhost :3000/comments/7/不像 500 (内部服务器错误)"
如果这很重要,其余的脚本已经在coffeescript中完成了吗?我读到控制器功能应该使用 .js.erb 所以希望这不会影响它。(我确定我的 js.erb 是错误的)