Javascript acts_as_votable gem

时间:2015-02-04 00:09:52

标签: javascript ruby-on-rails ajax ruby-on-rails-4 rubygems

好的,所以我使用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 %>

1 个答案:

答案 0 :(得分:0)

如果我了解您正在尝试正确执行的操作,我会根据用户的投票状态显示和隐藏按钮。然后在用户添加/删除它们时显示/隐藏它们。

<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 %>");