在我看来,我有一个使用simple_form gem的按钮:
<%= simple_form_for(:place_order, :url => "#{}", html: {id: "place_order" }) do |f| %>
<%= f.button :button, "Clear Cart", class: "btn btn-primary clearcart", id: "clear_cart", name: "clear_cart" %>
<%= f.button :submit, "Continue Shopping", class: "btn btn-success contShop", id: "continue_shopping", name: "continue_shopping" %>
<%= f.button :submit, "Proceed to Checkout", class: "btn btn-danger checkout", id: "proceed_to_checkout", name: "proceed_to_checkout" %>
<% end %>
我的CoffeeScript如下:
jQuery ->
$('button#clear_cart.btn.btn.btn-primary.clearcart').on 'click', (event) ->
$.post '/shopping/clear_cart'
$('input#continue_shopping.btn.btn-success.contShop').on 'click', (event) ->
$('#place_order').attr 'action', '/shopping'
$('input#proceed_to_checkout.btn.btn-danger.checkout').on 'click', (event) ->
$('#place_order').attr 'action', '/shopping/place_order'
$('input#place_an_inquiry.btn.btn-danger.checkout').on 'click', (event) ->
$('#place_order').attr 'action', '/shopping/review_order'
来自控制器的我的clear_cart动作如下:
def clear_cart
session[:product_quantity] = nil
redirect_to shopping_index_path
end
点击clear_cart按钮我发现一个JavaScript错误,其中clear_cart操作不可用,因为我已将其添加到路径文件中。
resources :shopping, :only => [:index] do
collection do
.....
get :clear_cart
post :clear_cart
end
end
我在这里做错了,它没有清除会话数据并将我返回到正确的区域?
答案 0 :(得分:1)
顺便说一句,你看起来应该让轨道通过JS进行清理和重定向。
我会选择类似的东西:
路由
resources :shopping, :only => [:index] do
collection do
.....
post :clear_cart
end
end
控制器
def clear_cart
session.delete(:product_quantity)
render json: {success: true, url: shopping_index_path}
end
JS
$('button#clear_cart.btn.btn.btn-primary.clearcart').on 'click', (event) ->
$.post '/shopping/clear_cart'.success(response) ->
window.location = response.url
答案 1 :(得分:1)
正如我对nesiseka的评论中提到的那样,我无法按照他建议的方式工作,所以我继续采用以下解决方案。
控制器:
def clear_cart
session.delete(:product_quantity)
if request.post?
redirect_to shopping_index_path
end
end
视图:
<%= simple_form_for(:place_order, :url => "#{}", html: {id: "place_order" }) do |f| %>
<%= f.button :submit, "Clear Cart", class: "btn btn-primary clearcart", id: "clear_cart", name: "clear_cart" %>
<%= f.button :submit, "Continue Shopping", class: "btn btn-success contShop", id: "continue_shopping", name: "continue_shopping" %>
<%= f.button :submit, "Proceed to Checkout", class: "btn btn-danger checkout", id: "proceed_to_checkout", name: "proceed_to_checkout" %>
<% end %>
CoffeeScript的:
jQuery(document).ready ->
$('input#clear_cart.btn.btn-primary.clearcart').on 'click', (event) ->
$('#place_order').attr 'action', '/shopping/clear_cart'