Rails-使用复选框更新数据库而不提交按钮

时间:2017-02-10 12:40:43

标签: jquery ruby-on-rails ajax

我是rails的新手,我正在开展一个在线购物项目。我想使用购物车中的复选框让用户选择是否购买产品。但我不喜欢复选框旁边的提交按钮。我知道我必须使用ajax来更新数据库而不使用提交按钮。但我没有做那个工作。以下是我的代码。

这是jquery ajax,

$(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

有人可以帮我这个吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

在js:

eclipse-feature

在config / routes.rb

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