首页 > 解决方案 > 尝试使用ajax更新rails索引中的复选框值

问题描述

在 Rails 应用程序中单击时,需要此 ajax 代码的一些帮助来更改复选框中 index.html.erb 中的布尔列。我是 javascript 新手。

<% @budget_histories.each do |budget_history| %>
 <tr>
  <li class="checkbox m-b-15">
   <label>
    <input type="checkbox" onchange="checkAllBudgetHistoryItems(this, '<%= budget_history.id %>');" name="budget_history_items" id="budget_history_item_<%= budget_history.id %>" value="<%= budget_history.id %>" />
    <i class="input-helper"></i>
   </label>
  </li>
 </tr>
<% end %>
function checkAllBudgetHistoryItems(el, id) {
    if (el.checked) {
      $.ajax({
        type: 'PUT',
        url: '/budget_histories/update',
        data: 'budget_history_item_' + id,
        success: function (data) {
          $("#budget_history_items_tbody input").prop('checked', false);
        }
      });
    } else {
      $.ajax({
        type: 'PUT',
        url: '/budget_histories/update',
        data: 'budget_history_item_' + id,
        success: function (data) {
          $("#budget_history_items_tbody input").prop('checked', true);
        }
      });
    }
  }

单击复选框时,如何使用 ajax 从我的数据库中更新 accept(boolean) 属性?

标签: javascriptruby-on-railsajax

解决方案


我已经解决了这样的问题:

  1. 创建控制器方法:
  def accept_budget    
    if @budget_history.toggle!(:accept)
      render json: {}, status: :ok
    else 
      render json: @budget_history.errors, status: :unprocessable_entity
    end
  end
  1. 创建路线
  resources :budget_histories do
    member do
      put :accept_budget
    end
  end
  1. 复选框 html
<li class="checkbox m-b-15">
  <label>
    <input type="checkbox" onchange="checkAllBudgetHistoryItems(this, '<%= budget_history.id %>');" name="budget_history_items" id="budget_history_item_<%= budget_history.id %>" value="<%= budget_history.id %>" />
    <i class="input-helper"></i>
  </label>
</li>
  1. 编辑脚本:
<script language="javascript">
  function checkAllBudgetHistoryItems(el, id) {
    if (el.checked) {
      $.ajax({
        type: 'PUT',
        url: '/budget_histories/' + id + '/accept_budget',
        data: 'budget_history_item_' + id,
        success: function (data) {
          $(el).prop('checked', true);
        }
      });
    } else {
      $.ajax({
        type: 'PUT',
        url: '/budget_histories/' + id + '/accept_budget',
        data: 'budget_history_item_' + id,
        success: function (data) {
          $(el).prop('checked', false);
        }
      });
    }
  }
</script>

推荐阅读