Javascript acts_as_votable gem

Javascript acts_as_votable gem

好的,所以我正在使用 acts_as_votable gem 来允许用户 add/remove 来自 collection 的书籍。我希望 add/remove 按钮可以在不重新加载页面的情况下工作,但找不到以这种方式实现按钮的任何地方,只是将其用作投票计数器。我不关心计票,只是add/remove。我的假设是我必须添加 fave.js.erb 和 unfave.js.erb 以及适当的 javascript 代码,但究竟是什么?提前致谢!

控制器的动作如下:

def fave
@book = Book.find(params[:id])
current_user.likes @book
respond_to do |format|
  format.html { redirect_to :back }
  format.json
  format.js
end
end
def unfave
@book = Book.find(params[:id])
current_user.dislikes @book
respond_to do |format|
  format.html { redirect_to :back }
  format.json
  format.js
end
end

还有 routes.rb

resources :books do
get "book/:page", :action => :index, :on => :collection
member do
  post "fave", to: "books#fave"
  post "unfave", to: "books#unfave"
end
end

那么从视图上看它们是这样调用的:

<% if user_signed_in? %>
<ul class="list-inline text-center">
<% if current_user.voted_up_for? @book %>
<li><%= button_to unfave_book_path(@book, method: :put, remote: true), class: "btn btn-default btn-danger", title: "Remove from Collection", data: {disable_with: "<span class='glyphicon glyphicon-minus'></span> Removing..."} do %>
<span class="glyphicon glyphicon-heart-empty"></span>  Remove from Collection
<% end %>
</li>
<% else %>
<li><%= button_to fave_book_path(@book, method: :put, remote: true), class: "btn btn-default btn-success", title: "Add to Collection", data: {disable_with: "<span class='glyphicon glyphicon-plus'></span> Adding..."} do %>
<span class="glyphicon glyphicon-heart"></span>  Add to Collection
<% end %>
</li>
<% end %>

如果我理解您正在尝试正确执行的操作,我会根据用户的投票状态显示和隐藏按钮。然后 show/hide 他们当用户 adds/removes 他们。

<ul class="list-inline text-center">
  <li data-book-id="<%= @book.id %>">
    <%= button_to unfave_book_path(@book, method: :put, remote: true), class: "btn btn-default btn-danger unfave #{'hidden' unless current_user.voted_up_for?(@book)}", title: "Remove from Collection", data: {disable_with: "<span class='glyphicon glyphicon-minus'></span> Removing..."} do %>
      <span class="glyphicon glyphicon-heart-empty"></span>  Remove from Collection
    <% end %>
    <%= button_to fave_book_path(@book, method: :put, remote: true), class: "btn btn-default btn-success fave #{'hidden' if current_user.voted_up_for?(@book)}", title: "Add to Collection", data: {disable_with: "<span class='glyphicon glyphicon-plus'></span> Adding..."} do %>
      <span class="glyphicon glyphicon-heart"></span>  Add to Collection
    <% end %>
  </li>
</ul>

我还假设您可能有多个 li 用于不同的书。

fave.js.erb 中,您可以:

var $li = $("li[data-book-id='<%= @book.id %>']");
$li.find('button.unfave').show();
$li.find('button.fave').hide();

unfave.js.erb 中,您可以:

var $li = $("li[data-book-id='<%= @book.id %>']");
$li.find('button.fave').show();
$li.find('button.unfave').hide();

如果你真的想保持你的模板原样,你可以重新渲染部分:

$('ul.list-inline').html("<%= j render 'path/to/a/partial', book: @book %>");