【问题标题】:Rails- Using check box to update database without submit buttonRails - 使用复选框更新数据库而无需提交按钮
【发布时间】:2017-02-10 21:12:50
【问题描述】:

我是 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

有人可以帮我解决这个问题吗?提前致谢!

【问题讨论】:

  • 您遇到的错误是什么?
  • 当我点击复选框时,数据库没有任何反应。
  • 什么是js错误?请求是否传递给控制器​​?
  • @jith 请求没有传递给控制器​​
  • web 控制台中一定有一些 js 错误显示。

标签: jquery ruby-on-rails ajax


【解决方案1】:

试试下面的代码:

在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();
        }});
    });
});

在 config/routes.rb 中

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

【讨论】:

  • 非常感谢!这比我原来的要好,但仍然有错误。 POST http://localhost:3000/save_data 500 (Internal Server Error)
  • 你是这个意思吗? 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
  • 1.错误日志显示在您的终端上。 2.右键->检查元素->控制台->红色的错误日志。
猜你喜欢
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 2013-02-18
  • 2012-07-03
  • 2012-11-30
  • 1970-01-01
  • 2017-12-18
相关资源
最近更新 更多