пытается обновить значение флажка в индексе рельсов с помощью ajax - PullRequest
1 голос
/ 14 июня 2019

Нужна небольшая помощь с этим кодом ajax для изменения логического столбца в index.html.erb в флажке при нажатии в приложении rails.Я новичок в 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);
        }
      });
    }
  }

Как я могу обновить атрибут accept (boolean) из моей базы данных с помощью ajax при установке флажка?

1 Ответ

0 голосов
/ 14 июня 2019

Я решил что-то вроде этого:

  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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...