在Rails服务器上基于条件恢复Jquery Droppable

时间:2018-10-23 01:22:35

标签: jquery ruby-on-rails ajax draggable

我目前正在开发Rails国际象棋应用程序。我一直在尝试找出实现Jquery拖放以在移动时更新片段的最佳方法。我已经能够在客户端成功移动部件,并使用ajax用新位置更新数据库。我的问题是,我想使用后端使用的计件方法检查移动是否有效,如果无效,请将其恢复到原始位置。

pieceMove.js

$(function() {

  // Draggable piece
  $('.piece_image').draggable({revert:true})

  // Droppable area that accepts piece image
  $('td').droppable({
    accept: '.piece_image',
    revert: true,
    drop: function(event, ui) {
      var piece_id = ui.helper[0].id;

      that = this

      // Sends the move's params to the update action in pieces controller
      $.ajax({
        type: 'PUT',
        dataType: 'script',
        url: '/update',
        data: { position_x: $(event.target).data('col'),
        position_y: $(event.target).data('row'), 
        piece_id: piece_id }
      })

      // Release piece to location moved to
      $(ui.draggable).detach().css({ top: 0, left: 0 }).appendTo(that);
    }
  })
})

piece_controller.rb

class PiecesController < ApplicationController

  def update
    @piece = Piece.find(params[:piece_id])

    # Updated piece positions
    x = params[:position_x].to_i
    y = params[:position_y].to_i

    if @piece.valid_move?(x, y)
      # Update database with current piece position
      @piece.update_attributes(position_x: x, position_y: y)
    else
      puts 'Invalid Move'
    end
  end

end

game / show.html.erb

<div class= "booyah-box col-10 offset-1">
  <div class="center">
    <h3>Game Show Page</h3>
    <%= link_to 'Home', root_path, class: 'btn btn-primary' %>
  </div>

    <div class="board-container">
      <table id="board" data-game_id="<%= @game.id %>">
          <% 8.times.each do |row| %>
          <tr id="row">
            <% 8.times.each do |col| %>
              <% piece = @game.pieces.where(position_x: col, position_y: row).first %>
              <td data-row="<%= row %>" data-col="<%= col %>">
                <% if piece.present? %>
                  <div class="piece_image" data-piece_id="<%= piece.id %>" data-piece_name="<%= piece.color %>_<%= piece.type %>" id="<%= piece.id %>" data-row="<%= row %>" data-col="<%= col %>">
                    <% image ="#{piece.color}_#{piece.type}.png" %>
                    <%= image_tag(image) %>
                  </div>
                <% end %>
              </td>
            <% end %>
          </tr>
          <% end %>
      </table>
    </div>
  </div>
</div>

routes.rb

Rails.application.routes.draw do

  devise_for :users
  root 'static_pages#index'

  put 'update', to: 'pieces#update'
  resources :games do
    resources :pieces, only: [:new, :create, :show, :index]  do
        put 'move', to: 'pieces#move'
    end
  end
end

我试图弄清楚是否有一种方法可以使用后端的方法来验证客户端的移动,因此在无效的情况下不会发生Drop。任何帮助将不胜感激。

0 个答案:

没有答案