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的文章真速度,,打个标志:
转载注明:
javaeye--
doabit..