Rails / Jquery:使用遥控器整合Bootstrap Toggle时出现问题:正确

时间:2018-12-08 15:17:39

标签: jquery ruby-on-rails twitter-bootstrap-3 erb

我是一名初级开发人员,我正在尝试将Bootstrap Toggle(http://www.bootstraptoggle.com/)集成到我的项目中。 该复选框显示良好,并且似乎可以在DB中使用,但是切换未正确切换。 Iam只是尝试切换一个布尔值(is_sent)并使用ajax和remote:true技巧更新我的购买状态。这是代码:

index.html.erb

      <% @purchases.order("created_at DESC").each do |purchase| %>
      <h2>Command n°<%= purchase.id %></h2>
         <% @orders.where(id: purchase.order_id).each do |order| %>          
      <h3> <strong>Complete Information:</strong> </h3>
      <h4> Command sent ? ? </h4>

    <%= form_for purchase do |f| %>
    <%= f.check_box :is_sent, 'data-toggle' => 'toggle', 'data-onstyle' 
    => "danger", id: 'toggle1', 'data-style' => "slow",
         data: {
        remote: true,
        url: url_for(action: :update, id: purchase.id),
        method: "PATCH"
        }  %>
        <% end %>

    <script src="https://gitcdn.github.io/bootstrap- 
    toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
    <link href="https://gitcdn.github.io/bootstrap- 
    toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/>
    <script>
    $(function() {   
        $('toggle1').bootstrapToggle();
      })
    </script>

admin_purchases_controller:

  def update
     @purchase = Purchase.find(params[:id])
     status = !@purchase.is_sent
     @purchase.is_sent = status
     @purchase.save
  end

路线:

  namespace :admin do
    resources :purchases, only: [:index, :update] 
  end

现在您可以看到,当我单击切换开关时,该值已很好地保存在数据库中:

 Started PATCH "/admin/purchases/2" for 127.0.0.1 at 2018-12-08 
 16:01:27 +0100
 Processing by Admin::PurchasesController#update as JS
 Parameters: {"id"=>"2"}
 User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" 
 = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
 Purchase Load (2.4ms)  SELECT  "purchases".* FROM "purchases" WHERE 
 "purchases"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
(0.7ms)  BEGIN
User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = 
$1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
SQL (1.8ms)  UPDATE "purchases" SET "is_sent" = $1, "updated_at" = $2 
WHERE "purchases"."id" = $3  [["is_sent", "f"], ["updated_at", "2018- 
12-08 15:01:27.879657"], ["id", 2]]
(0.5ms)  COMMIT
Rendering admin/purchases/update.js.erb
Rendered admin/purchases/update.js.erb (1.0ms)
Completed 200 OK in 203ms (Views: 126.6ms | ActiveRecord: 6.4ms)

但是第一次我单击按钮时,它没有切换。之后,它的开关正确,但是值不是好的。。。

也许我必须设置动态ID,因为要进行迭代,但是在那种情况下,我不知道该怎么做..

对不起,我的英语不好,我希望有人能帮忙! 预先感谢

0 个答案:

没有答案