rails3 +jquery-ui+acts_as_list实现可拖曳排序

1.建立新的项目
rails new jsort -J


2.修改Gemfile,

gem 'rails3-generators' #用来安装jquery等
gem 'acts_as_list'

bundle install 安装gem

3.安装jquery和jquery ui,并且修改application.rb
rails g jquery:install --ui

在 application.rb中添加
config.action_view.javascript_expansions[:defaults] = %w(jquery jqueryui rails)


4.生成文章测试,并且修改post.rb添加acts_as_list
rails g scaffold post title:string body:text position:integer


#post.rb
class Post < ActiveRecord::Base
acts_as_list
end

5.移除index.html.修改 routes
rm public/index.html
#修改routes.rb
root :to=>"posts#index"

6.修改posts/_form.html.erb,去掉position列,添加几个文章测试下
   <div class="field">
<%= f.label :position %><br />
<%= f.text_field :position %>
</div>

7.建立application.js,添加以下代码,
 $(function(){
sortList("posts","tr");//调用排序方法,对post对行排序
})
//排序方法,可实现多次调用,obj:要排序的model复数名,item:排序元素,jqeury官方文发写的是对li进行排序,但可以对表格排序,具体访谈录请参考jquery ui文档
function sortList(obj,item)
{
$('#'+obj).sortable({
axis: 'y',
dropOnEmpty: false,
//handle: '.handle',
cursor: 'crosshair',
items: item,
opacity: 0.4,
scroll: true,
update: function(){
$.ajax({
type: 'post',
data: $('#'+obj).sortable('serialize'),
dataType: 'script',
complete: function(request){
$('#'+obj).effect('highlight');
},
url: ""+obj+"/sort"});
}
});
}


8.修改posts/index.html.erb

<h1>Listing posts</h1>

<table id="posts">
<tr>
<th>Title</th>
<th>Body</th>
<th>Position</th>
<th></th>
<th></th>
<th></th>
</tr>

<%=render :partial => "post", :collection => @posts%>
</table>

<br />

<%= link_to 'New Post', new_post_path %>


9.新建posts/_post.html.erb

<tr id="post_<%=post.id %>">
<td><%= post.title %></td>
<td><%= post.body %></td>
<td><%= post.position %></td>
<td><%= link_to 'Show', post %></td>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
<td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>


10.把 application.js添加到application.html.erb
<%= javascript_include_tag "application" %>


11.在posts_controller.rb中添加排序方法

def sort
@posts = Post.all
@posts.each do |post|
post.position = params['post'].index(post.id.to_s) + 1
post.save
end
render :nothing => true
end

12.修改 routes.rb最终为:
  resources :posts do
collection do
post :sort
end
end

root :to=>"posts#index"


最终代码:
git://github.com/doabit/jquery-sort-example.git


另:有个网站抓取JE的文章真速度,,打个标志:
转载注明:[url=http://www.iteye.com]javaeye[/url]--[url=http://doabit.iteye.com/]doabit[/url]..
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值