【发布时间】:2015-11-01 20:20:16
【问题描述】:
我有一个模型,书,有一个 has_many 关联,拥有。我已经设置好了,用户可以点击一个按钮将这本书添加到他们的收藏中。控制器如下所示:
def create
@book.owns.where(user_id: current_user.id).first_or_create
@own = Own.where(user_id: current_user.id, book_id: @book.id)
Own.update(@own, :quantity => "1")
respond_to do |format|
format.html { redirect_to @book}
format.js
end
end
视图如下所示:
<% if user_signed_in? && current_user.owns?(@book) %>
<%= link_to book_own_path(@book), method: :delete, remote: true, class: "btn btn-danger btn-circle", title: "Remove from collection", data: { toggle: "tooltip", disable_with: "<span class='fa fa-minus'></span>"} do %><span class="fa fa-heart-o"></span><% end %>
<% else %>
<%= link_to book_own_path(@book), method: :post, remote: true, class: "btn btn-success btn-circle", title: "Add to collection", data: { toggle: "tooltip", disable_with: "<span class='fa fa-plus'></span>"} do %><span class="fa fa-heart"></span><% end %>
<% end %>
因此,当单击该按钮时,它会自动将数量 1 添加到他们的库存中。我想做的是让用户能够从图书展示视图更新他们拥有的数量,所以我添加了这个:
<% if user_signed_in? && current_user.owns?(@book) %>
<span id="<%= @book.id %>_quantity">
<% Own.where(:user_id => current_user.id, :book_id => @book.id).each do |z| %>
<% if z.quantity == 1 %>
<form>
You own <input type="text" placeholder="<%= z.quantity %>" id="quantity" name="quantity" size="1" class="text-center" /> copies of this book
<input type="submit" onclick="<% Own.update(@own, :quantity => params[:quantity]) %>.submit();" hidden />
<form>
<% else %>
<form>
You own <input type="text" placeholder="<%= z.quantity %>" id="quantity" name="quantity" size="1" class="text-center" /> copies of this book
<input type="submit" onclick="<% Own.update(@own, :quantity => params[:quantity]) %>.submit();" hidden />
<form>
<% end %>
<% end %>
<br />
</span>
<% end %>
当我点击输入时,上面确实会更新自己的数量,但它会将我重定向到相同的 url,并在末尾添加 ?quantity=1(或任何数量值)。除非刷新页面,否则它也不会在输入占位符中显示数量。
我的问题是,有没有更好的方法来解决这个问题,或者有没有办法实际显示占位符的值。另外,如何在后台提交表单而不是刷新页面的位置进行设置?
【问题讨论】:
标签: javascript jquery ruby-on-rails ajax