[英]Javascript acts_as_votable gem
好的,所以我使用acts_as_votable gem允許用戶添加/刪除集合中的書籍。 我希望添加/刪除按鈕能夠在不重新加載頁面的情況下工作,但找不到以這種方式實現按鈕的任何地方,只是將其用作投票計數器。 我不在乎數票,只需添加/刪除即可。 我的假設是我必須使用適當的javascript代碼添加fave.js.erb和unfave.js.erb,但是究竟是什么呢? 提前致謝!
以下是控制器的操作:
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 %>
如果我了解您要正確執行的操作,則會根據用戶的投票狀態顯示和隱藏按鈕。 然后在用戶添加/刪除它們時顯示/隱藏它們。
<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
S代表不同的書。
在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 %>");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.