Ruby on Rails 的Active Record之Acts As List和Acts As Tree

Acts As List实例:
在子表中加parent_idposition

定义:
class Parent < ActiveRecord::Base
 has_many :children, :order => :position
end
class

Child < ActiveRecord::Base
 belongs_to :parent
 acts_as_list :scope => :parent_id
#:scope 指定在parent_id相同范围内.
end

向表中添加数据:
parent = Parent.new
%w{ One Two Three Four}.each do |name|
 parent.children.create(:name => name)
end
parent.save

定义显示方法:
def display_children(parent)
 puts parent.children.map {|child| child.name }.join(", ")
end

调用实例:
display_children(parent) #=> One, Two, Three, Four

puts parent.children[0].first? #=> true
#使用last?(), first?()判断行位置

two = parent.children[1]
puts two.lower_item.name  #=> Three
puts two.higher_item.name #=> One
#使用.lower_item访问下一行数据, 使用.higher_item访问上一行数据,使用

parent.children[0].move_lower
parent.reload

display_children(parent) #=> Two, One, Three, Four
#使用mover_lower(), mover_higher()可移动行数据
#使用parent.reload刷新数据

parent.children[2].move_to_top
parent.reload
display_children(parent) #=> Three, Two, One, Four
#使用move_to_top(), move_to_bottom()移动行数据

parent.children[2].destroy
parent.reload
display_children(parent) #=> Three, Two, Four
#一行数据删除后其下面的行会自动跟上

Acts As Tree实例:
向子表新增parent_id (int), 并将设定为表内关联键

定义方法:
class Category < ActiveRecord::Base
 acts_as_tree :order =>"name"
end

向表格添加数据:
root = Category.create(:name => "Books")
fiction = root.children.create(:name =>"Fiction")
non_fiction = root.children.create(:name => "Non Fiction")

non_fiction.children.create(:name =>"Computers")
non_fiction.children.create(:name =>"Science")
non_fiction.children.create(:name =>"Art History")

fiction.children.create(:name =>"Mystery")
fiction.children.create(:name => "Romance")
fiction.children.create(:name =>"Science Fiction")

定义显示方法:
def display_children(parent)
 puts parent.children.map {|child| child.name }.join(", ")
end

调用实例:
display_children(root) # Fiction, Non Fiction

sub_category = root.children.first
puts sub_category.children.size #=> 3
display_children(sub_category) #=> Mystery, Romance, Science Fiction

non_fiction = root.children.find(:first, :conditions => "name = ‘Non Fiction’")

display_children(non_fiction) #=> Art History, Computers, Science

puts non_fiction.parent.name #=> Books

:counter_cache => true+children_count段也可以在这里使用.用来自动计算子表行数.

此条目发表在 Ruby on Rails 分类目录。将固定链接加入收藏夹。

Ruby on Rails 的Active Record之Acts As List和Acts As Tree》有 1 条评论

发表评论