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 條評論

發表評論