我在我的Rails应用程序中使用以下代码来生成喜欢/不喜欢的按钮。我希望图标能够自动更改,而无需刷新页面。我在这里搜索了一些问题,但找不到任何与我的情况相关的内容。我非常感谢您提供的任何帮助。
<div class="single-heart-this">
<% if user_signed_in? %>
<% if current_user.liked? @pride %>
<%= link_to dislike_pride_path(@pride), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Like', toggle_href: like_pride_path(@pride), id: @pride.id } do %>
<span class="heart-icon" style="background-position: 0px -290px;" data-id="<%= @pride.id %>"></span>
<% end %>
<% else %>
<%= link_to like_pride_path(@pride), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Dislike', toggle_href: dislike_pride_path(@pride), id: @pride.id } do %>
<span class="heart-icon" style="background-position: 0px -256px;" data-id="<%= @pride.id %>"></span>
<% end %>
<% end %>
<% end %>
<span class="heart-no" data-id="<%= @pride.id %>"><%= @pride.get_likes.size %></span>
</div>
答案 0 :(得分:2)
我这样做:
#config/routes.rb
resources :pride
#app/controllers/prides_controller.rb
Class PrideController < ApplicationController
def update
... #-> logic here
respond_to do |format|
format.js #-> loads app/views/pride/update.js.erb
end
end
end
#app/views/pride/update.js.erb
$(".single-heart-this").html("<%=j render partial: 'vote', locals: { pride: @pride } %>")
#app/views/controller/your_view.html.erb
<div class="single-heart-this">
<%= render partial: "vote", locals: { pride: @pride } %>
</div>
#app/views/controllers/_vote.html.erb
<% if user_signed_in? %>
<%= link_to pride_path(@pride), class: 'vote', method: :put, remote: true, id: @pride.iddo %>
<% style = current_user.liked?(@pride)? "-290px" : "-256px"
<span class="heart-icon" style="background-position: 0px <%= style %>;" data-id="<%= @pride.id %>"></span>
<% end %>
<% end %>