要為Ruby on Rails程式加入拖曳排序功能~我們可以使用sortable_element helper function
他可近呼自動地為程式加入拖曳排序功能
script/plugin install git://github.com/rails/acts_as_list.git
這個程式中會用到acts_as_list插件,請先行安裝~ 我們現在先用scaffold建立基本CRUD功能
ruby generate scaffold task title:string position:integer
現在我們修改Task Model如下
class Task < ActiveRecord::Base
acts_as_list
end
這樣便可以將其變成有序列表~
然後我們把Tasks Controller的index Action修改如下
def index
@tasks = Task.find(:all, :order => :position)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @tasks }
end
end
這樣顯示時便會依照List的順序~
現在在layout中的tasks.html.erb的head中加入一行
<%= javascript_include_tag :defaults %>
然後修改index View~
<h1>Listing tasks</h1>
<ul id='tasks'>
<% for task in @tasks %>
<li id='task_<%= task.id %>'>
<%=h task.title %>
<%= link_to 'Edit', edit_task_path(task) %>
<%= link_to 'Destroy', task, :confirm => 'Are you sure?', :method => :delete %>
</li>
<% end %>
</ul>
<br />
<%= link_to 'New task', new_task_path %>
<%= sortable_element 'tasks', :url => {:action => :sort} , :constraint => false, :tree => true, :dropOnEmpty => true, :complete => visual_effect(:highlight, 'tasks') %>
这里加上了高亮显示的功能,可以支持树的拖拉
現在便啟用了拖曳的功能了,不過拖曳後重新整理,位置並沒有更新
那是因為我們還沒有增加sort Action
現在到Tasks Controller中加入sort Action
def sort
params[:tasks].each_with_index do |id, position|
Task.update(id, :position => position + 1)
end
render :nothing => true
end