我正在尝试创建类似按钮,允许用户喜欢帖子。然后按钮变换为不同的按钮,允许用户不同于帖子。我做到了,但我认为这是错误的。
我的代码
<div class='likes'>
<% if user_signed_in?%>
<% unless current_user.likes?(post) %>
<%= link_to image_tag('unlike.png', alt: 'unlike'), like_path(post) %>
<% else %>
<%= link_to image_tag('like.png', alt: 'like'), unlike_path(post) %>
<% end %>
<% if post.likers_count >0 %>
<%= post.likers_count %>
<% end %>
<% end %>
</div>
当我点击按钮时整页重新加载,但我只需要重新加载一个按钮。我怎么能这样做?
答案 0 :(得分:0)
这样做:
#config/routes.rb
resources :posts do
match :vote, on: :member, via: [:post, :delete]
end
#app/controllers/posts_controller.rb
class PostsController < ApplicationController
def vote
@post = Post.find params[:id]
if request.post?
... vote up
elsif request.delete?
... vote down
end
respond_to do |format|
format.js #-> only XHR allowed
end
end
end
#app/views/posts/vote.js.erb
$(".likes").html("<%=j render 'posts/vote' %>");
#app/views/posts/_vote.html.erb
<% if user_signed_in?%>
<% method = current_user.likes?(@post) ? ["post", ""] : ["delete", "un"] %>
<%= link_to image_tag("#{method[1]}like.png", alt: "#{method[1]}like"), post_vote_path(@post), method: method[0].to_sym, remote: true %>
<%= @post.likers_count if @post.likers_count > 0 %>
<% end %>
在posts#show
视图中,您应该这样做:
#app/views/posts/show.html.erb
<div class="likes">
<%= render partial: "vote" %>
</div>