【发布时间】:2016-01-27 07:00:43
【问题描述】:
我可以点击一次链接,计数会更新,但之后点击不会更新,也不会更新到数据库中(查看控制台)。
index.html.haml
.votes
- if current_user.liked? skit
= link_to unlike_skit_path(skit), method: :get, remote: true, class: "unlike-post" do
.upvote
%span.upvote-link
%i.fa.fa-caret-up
.vote-count= skit.votes_for.size
- else
= link_to like_skit_path(skit), method: :get, remote: true, class: "like-post" do
.upvote
%span.upvote-link
%i.fa.fa-caret-up
.vote-count= skit.votes_for.size
routes.rb
resources :skits do
resources :challenges
member do
get "like", to: "skits#like"
get "unlike", to: "skits#unlike"
end
end
不像.js.erb
$('.unlike-post').bind('ajax:success', function(){
$(this).find('.vote-count').html('<%= escape_javascript @skit.votes_for.size.to_s %>');
});
like.js.erb
$('.like-post').bind('ajax:success', function(){
$(this).find('.vote-count').html('<%= escape_javascript @skit.votes_for.size.to_s %>');
});
skits_controller.rb
def like
@skit.liked_by current_user
respond_to do |format|
format.html { redirect_to skits_path, notice: 'Successfully voted!' }
format.js { render layout: false }
end
end
def unlike
@skit.unliked_by current_user
respond_to do |format|
format.html { redirect_to skits_path, notice: 'Successfully voted!' }
format.js { render layout: false }
end
end
编辑
从底部应用帮助后,不保存到数据库中:
存入数据库时:
【问题讨论】:
-
不要使用
GET请求来创建或销毁资源。 GET 请求保存在浏览器历史记录中。而是使用POST /skits/1/likes之类的东西来创建一个喜欢和DELETE /likes/:id来不喜欢。 -
@max 谢谢你,你认为你可以发布一个例子吗?另外,用 PUT 代替呢?
-
你可以使用
PUT,但它不是很RESTful。而PUT /skits/1/like更像是一个过程。我今天没有时间输入完整的答案,对不起。然而,这是一个非常常见的场景,你应该能够在网上找到很多例子。
标签: jquery ruby-on-rails ajax ruby-on-rails-4 acts-as-votable