首页
/ sortableGem 使用与技术文档

sortableGem 使用与技术文档

2024-12-23 19:12:20作者:晏闻田Solitary

1. 安装指南

sortable Gem 是一个用于排序 ActiveRecord 项的插件,支持多作用域和列表。以下是安装步骤:

  • 使用 gem 安装:
    gem install shuber-sortable --source http://gems.github.com
    
  • 或者使用 script/plugin 安装:
    script/plugin install git://github.com/shuber/sortable.git
    

确保您的 ActiveRecord 版本大于等于 2.0.0。

2. 项目的使用说明

sortable 插件允许您按照类似 http://github.com/rails/acts_as_list 的方式对 ActiveRecord 对象进行排序,但增加了对多个作用域和列表的支持。

以下是使用示例:

简单使用

class Todo < ActiveRecord::Base
  sortable :scope => :project_id
end

@todo = Todo.create(:description => '做某事', :project_id => 1)
@todo_2 = Todo.create(:description => '做其他事', :project_id => 1)
@todo_3 = Todo.create(:description => '另一个任务', :project_id => 2)

多个作用域

当需要按照不同的作用域排序时,可以传递一个作用域数组。

class Story < ActiveRecord::Base
  sortable :scope => [:project_id, :sprint_id]
end

多个列表

如果你的项目需要允许客户和开发者分别对任务列表进行优先级排序,那么可以使用多个列表功能。

class Todo < ActiveRecord::Base
  sortable :scope => :project_id, :column => :client_priority, :list_name => :client
  sortable :scope => :project_id, :column => :developer_priority, :list_name => :developer
end

切换作用域

当作用域内的属性发生变化时,相关项将自动切换列表。

class Todo < ActiveRecord::Base
  sortable :scope => :project_id
end

@todo = Todo.create(:description => '做某事', :project_id => 1)
@todo_2 = Todo.create(:description => '做其他事', :project_id => 1)

@todo.project_id = 2
@todo.save

3. 项目API使用文档

以下是 sortable 插件提供的一些实例方法:

  • add_to_list!(list_name = nil):将当前项添加到指定列表的末尾并保存。
  • first_item(list_name = nil):返回关联列表中的第一个项。
  • first_item?(list_name = nil):判断当前项是否是指定列表的第一个项。
  • higher_items(list_name = nil):返回指定列表中当前项以上的所有项。
  • in_list?(list_name = nil):判断当前项是否在指定列表中。
  • insert_at!(position = 1, list_name = nil):将当前项插入到指定列表的特定位置并保存。
  • item_at_offset(offset, list_name = nil):返回指定列表中当前项偏移量为 offset 的项。
  • last_item(list_name = nil):返回关联列表中的最后一个项。
  • last_item?(list_name = nil):判断当前项是否是指定列表的最后一个项。
  • last_position(list_name = nil):返回指定列表中最后一个项的位置。
  • lower_items(list_name = nil):返回指定列表中当前项以下的所有项。
  • move_down!(list_name = nil):将当前项在指定列表中向下移动一位并保存。
  • move_up!(list_name = nil):将当前项在指定列表中向上移动一位并保存。
  • move_to_bottom!(list_name = nil):将当前项移动到指定列表的底部并保存。
  • move_to_top!(list_name = nil):将当前项移动到指定列表的顶部并保存。
  • next_item(list_name = nil):返回指定列表中当前项下一个项。
  • previous_item(list_name = nil):返回指定列表中当前项上一个项。
  • remove_from_list!(list_name = nil):从指定列表中移除当前项并保存。
  • sortable_scope_changed?:判断当前项是否有作用域内的属性发生变化。
  • sortable_scope_changes:存储作用域内已更改的属性数组。

4. 项目安装方式

项目的安装方式已在安装指南部分说明,可通过 gem 安装或 script/plugin 安装。请参考安装指南部分进行操作。

登录后查看全文
热门项目推荐

项目优选

收起