2

Подключил gem 'ranked-model' для drag-and-drop сортировки таблицы. Пример реализации брал отсюда http://benw.me.

Строки таблицы перемещаются - но при перезагрузке страницы, измененное расположения строк не сохраняется. Подскажите как побороть данную проблему?

Контроллер:

class TasksController < ApplicationController

  def index
    @tasks = Task.rank(:row_order).all
    @task = Task.new
  end

  def update_row_order
    @task = Task.find(task_params[:task_id])
    @task.row_order_position = task_params[:row_order_position]
    @task.save

    render nothing: true # this is a POST action, updates sent via AJAX, no view rendered
  end

  def show
    @task = Task.find(params[:id])
  end

  def create
    @task = Task.new(task_params)

    respond_to do |format|
      if @task.save
        format.html { redirect_to @task, notice: 'Task was successfully created.' }
        format.js {}
        format.json { render json: @task, status: :created, location: @task }
      else
        format.html { render action: "new" }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    @task = Task.find(params[:id])

    respond_to do |format|
      if @task.update(task_params)
        format.json { respond_with_bip(@task) }
        format.html { redirect_to(@task, :notice => 'Task was successfully updated.') }
      else
        format.json { respond_with_bip(@task) }
        format.html { render :edit }
      end
    end

  end

  def edit
    @task = Task.find(params[:id])
    respond_to do |format|
      format.js {}
    end
  end

  def destroy
    @task = Task.find(params[:id])
    @task.destroy
    respond_to do |format|
      format.html { redirect_to products_path, success: 'Product destroyed successfully' }
      format.js {}
    end

  end

  private
  # Use callbacks to share common setup or constraints between actions.
  def set_task
    @task = Task.find(params[:id])
  end

  private
  def task_params
    params.require(:task).permit(:task_id, :name, :row_order_position)
  end

end

Скрипт:

assets/javascript/update_things_row_order.js.coffee:

jQuery ->
  if $('#sortable').length > 0
    table_width = $('#sortable').width()
    cells = $('.table').find('tr')[0].cells.length
    desired_width = table_width / cells + 'px'
    $('.table td').css('width', desired_width)

    $('#sortable').sortable(
      axis: 'y'
      items: '.item'
      cursor: 'move'

      sort: (e, ui) ->
        ui.item.addClass('active-item-shadow')
      stop: (e, ui) ->
        ui.item.removeClass('active-item-shadow')
        # highlight the row on drop to indicate an update
        ui.item.children('td').effect('highlight', {}, 1000)
      update: (e, ui) ->
        item_id = ui.item.data('item-id')
        console.log(item_id)
        position = ui.item.index() # this will not work with paginated items, as the index is zero on every page
        $.ajax(
          type: 'POST'
          url: '/tasks/update_row_order'
          dataType: 'json'
          data: { task: {task_id: item_id, row_order_position: position } }
        )
    )

View:

tasks/index.html.erb:

<div class="container" xmlns="http://www.w3.org/1999/html">
  <h1>TASK#PAGE</h1>

  <%= form_for(@task, remote: true) do |f| %>
      <div class="input-group">
        <%= f.text_field :name, class: 'form-control ' %>
        <span class="input-group-btn">
      <%= f.submit 'Добавить', class: 'btn btn-success btn-secondary' %>
      </span>
      </div>
  <% end %>

  <br>
  <table id="sortable" class="tasks table table-striped">

    <%= render @tasks %>

  </table>
</div>

partial:

tasks/_task.html.erb

<tr id="row_<%= task.id %>" data-item-id=<%= "#{task.id}" %> class="item">
  <td><%= check_box_tag(:task) %></td>
  <td id="task-name" style="width: 90%"><%= best_in_place task, :name %></td>

  <td><%= link_to '<i class="glyphicon glyphicon-trash"></i>'.html_safe, task_path(task), remote: true,
                  class: 'btn btn-danger btn-xs',
                  method: :delete,
                  data: {confirm: 'Вы уверены?'} %></td>
</tr>

Ошибки при отработке AJAX в браузере не вижу

AJAX запрос (консоль браузера)

Routes.rb:

Rails.application.routes.draw do

  get 'home/index'

  get 'devise' => 'sessions#new'

  devise_for :users

  resources :profiles
  resources :projects
  resources :tasks do
    post :update_row_order, on: :collection
  end

  root 'home#index'

Модель:

class Task < ActiveRecord::Base
  include RankedModel
  ranks :row_order

  belongs_to :user
  belongs_to :project
end
5
  • Выкладывай контроллер, форму, javascript, лог из консоли Rails, и самое главное - роуты.
    – MAXOPKA
    3 фев 2016 в 7:57
  • Добавил view, Routes.rb, javascript, модель, контроллер + скриншот консоли браузера 3 фев 2016 в 9:51
  • Судя по всему проблема в там что я при помощи AJAX добавляю и удаляю данные в таблице. Если сделать таблицу как в примере - без AJAX отрабатывает нормально. Теперь не понимаю что не так с рендерингом было и как нужно правильно его настроить 3 фев 2016 в 10:07
  • Скриншот консоли Rails нужен, либо логи.
    – MAXOPKA
    3 фев 2016 в 10:19
  • 1
    post :update_row_order, on: :collection замените на post :update_row_order, on: :member. Вы ведь обращаетесь к члену коллекции, а не к коллекции
    – MAXOPKA
    3 фев 2016 в 10:21

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Посмотрите другие вопросы с метками или задайте свой вопрос.