2017-02-10 85 views
0

我是rails新手,我正在開發一個在線購物項目。我想在購物車中使用複選框讓用戶選擇是否購買產品。但我不喜歡複選框旁邊的提交按鈕。我知道我必須使用ajax來更新數據庫而無需提交按鈕。但是我沒有完成這項工作。以下是我的代碼。Rails-使用複選框來更新數據庫而無需提交按鈕

這裏是jQuery的阿賈克斯,

$(document).ready(function(){ 
    $(".checkbox_submit").change(function(){ 
     $.ajax({url: {:action => create}, success: function(result){ 
      $(this).parents('form:first').submit(); 
     }}); 
    }); 
}); 

這是我的看法,第一TD是複選框

<tr> 
    <td style="width: 5%;"> 
     <%= form_for cart_item, url: cart_item_path(cart_item.product_id), remote: true do |f| %> 
      <%= f.check_box(:buy_now, class: "checkbox_submit") %> 
     <% end %> 
    </td> 
    <td style="width: 20%;" > 
     <%= link_to(product_path(cart_item.product)) do %><%= image_tag(cart_item.product.image.thumb.url) %><% end %> 
    </td> 
    <td style="width: 30%;"><%= link_to(cart_item.product.title, product_path(cart_item.product)) %></td> 
    <td><%= cart_item.product.price %></td> 
    <td> 
     <%= form_for cart_item, url: cart_item_path(cart_item.product_id, remote: true) do |f| %> 
      <%= f.select :quantity, 1..cart_item.product.storage, class: "select_submit" %> 
     <% end %> 
    </td> 
    <td><strong>¥<%= cart_item.product.price * cart_item.quantity %></strong></td> 
    <td><%= link_to(cart_item_path(cart_item.product_id), method: :delete) do %><i class="fa fa-trash-o" aria-hidden="true"></i><% end %></td> 
</tr> 

這是我的控制器

def update 
     @cart = current_cart 
     @cart_item = @cart.cart_items.find_by(product_id: params[:id]) 
     if @cart_item.product.storage >= cart_item_params[:quantity].to_i 
      @cart_item.update(cart_item_params) 
      redirect_to carts_path 
     else 
      redirect_to carts_path, alert: "exceed the storage" 
     end 

end 

莫非任何人都可以幫助我?提前致謝!

+0

什麼是錯誤您收到? – jithya

+0

當我點擊複選框時,數據庫沒有任何反應。 – lacfo

+0

什麼是js錯誤?請求傳遞給控制器​​? – jithya

回答

0

試試下面的代碼:

在JS:

$(document).ready(function(){ 
    $(".checkbox_submit").change(function(){ 
     var src = $(this); 
     $.ajax({ 
      type: "post", 
      url: "/sava_data", 
      success: function(result){ 
      src.parents('form:first').submit(); 
     }}); 
    }); 
}); 

在配置/ routes.rb中

post '/save_data' => 'controller_name#action' 
+0

非常感謝!這比我原來的更好,但仍然有錯誤。 'POST http:// localhost:3000/save_data 500(內部服務器錯誤)' – lacfo

+0

您可以向我發送錯誤日誌 – puneet18

+0

您的意思是? 'send @ jquery.self-bd7ddd3 ... .js?body = 1:10255 ajax @ jquery.self-bd7ddd3 ... .js?body = 1:9739(anonymous)@ cart_change.self-e3000ed ... .js?body = 1 :15 dispatch @ jquery.self-bd7ddd3 ... .js?body = 1:5227 elemData.handle @jquery.self-bd7ddd3 ... .js?body = 1:4879 ' – lacfo

相關問題