带有JQuery Sortable问题的Ruby on Rails

时间:2012-06-15 06:24:32

标签: jquery ruby-on-rails ruby-on-rails-3 jquery-ui jquery-ui-sortable

我已经搜遍了这个解决方案,但找不到符合我特定问题的解决方案,或者我能理解的问题。我有一个RoR应用程序,允许人们使用拖放界面使用JQuery UI的Sortable对“选举”进行“投票”。我将拖放列表中的每个元素称为“首选项”。所有“首选项”都从未排序(sortable2)列开始,用户将它们拖到排序列(sortable1)。我想只保存用户拖入“sortable1”的“首选项”的位置。

对于拖放,我使用了JQuery UI的Sortable,界面非常好。但是,我在实际提交每个首选项的位置时遇到问题,最终将其记录在数据库中。这是我的第一个网络应用程序,我对此非常陌生。非常感谢您提前寻求帮助。这是我的代码:

在创建新投票的视图中:

<script>
$(function() {
  $( "ul.droptrue" ).sortable({
  connectWith: "ul"
});

$( "#sortable1, #sortable2" ).disableSelection();
});

<ul id="sortable1" class='droptrue'>
Preferences:

</ul>

<ul id="sortable2" class='droptrue'>
Unranked candidates:
  <% @vote.preferences.each do |preference| %>
    <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>      
    <%= preference.candidate.name %></li>
  <% end %>
</ul>

根据我在网上找到的建议,我将'sort'添加到我的votes_controller.rb:

class VotesController < ApplicationController
  respond_to :html, :json

  # I added this 
  def sort
      params[:preferences].each_with_index do |id, index|
         @vote.preferences.update(['position=?', index+1], ['id=?', id])
      end
      render nothing: true
  end

在vote.rb中,我有:

class Vote < ActiveRecord::Base
    # ...
    has_many :preferences
    accepts_nested_attributes_for :preferences, allow_destroy: true, reject_if: lambda { |c| c.values.all?(&:blank?) }
end

在preference.rb中,我有:

class Preference < ActiveRecord::Base
   attr_accessible :position
   belongs_to :vote, dependent: :destroy
end

在routes.rb中,我有:

resources :votes do
   put :sort
end

老实说,如果有人成为我的英雄并帮助兄弟出去,那将是我的一天。我搜索了很长时间以避免发布可能多余的内容,但我在这里和通过谷歌找到的所有内容都无法帮助我。谢谢。

1 个答案:

答案 0 :(得分:0)

我们的做法是:

  1. 在“可排序”上使用'stop' event
  2. 在stop事件中,使用索引遍历“ul”的所有元素。索引是项目的“排序位置”。
  3. 制作ajax POST以修改所有项目的位置。