跳轉到內容

Ruby on Rails/ActiveRecord/acts as

來自華夏公益教科書,開放的書籍,開放的世界

acts_as_list

[編輯 | 編輯原始碼]

Acts as List 將向 ActiveRecord 模型新增方法,這些方法提供將記錄訪問為列表的方法。

acts_as_list指令將向 ActiveRecord 物件新增方法,以使每個例項充當列表中的一個元素。acts_as_list接受兩個配置選項

  • column : 用於儲存位置的列的名稱(預設值為position)
  • scope : 限制要考慮為列表的內容。給定一個符號,它將附加 "_id"(如果還沒有)並將其用作外部索引鍵限制。還可以為它提供一個完整的字串,如果您需要比僅外部索引鍵更嚴格的範圍,該字串將被內插。示例acts_as_list :scope => ‘todo_list_id = #{todo_list_id} AND completed = 0’

例項方法

[編輯 | 編輯原始碼]

指定了 acts_as_list 指令的模型的每個例項將自動包含用於將記錄作為列表處理的方法

  • decrement_position
  • first?
  • higher_item
  • in_list?
  • increment_position
  • insert_at
  • last?
  • lower_item
  • move_higher
  • move_lower
  • move_to_bottom
  • move_to_top
  • remove_from_list

更改列表中專案位置的方法會立即影響永續性資料。例如,呼叫move_to_top將立即生效。

  class Person < ActiveRecord::Base
    acts_as_list
  end

假設資料庫中有三個人(Joe、Bob 和 Jane,最初按此順序)

 p = Person.find_by_name('Joe')
 p.first?
 => true
 p.in_list?
 => true
 p.move_to_bottom
 p.first?
 => false
 p.last?
 => true

acts_as_tree

[編輯 | 編輯原始碼]

acts_as_tree指令將向 ActiveRecord 物件新增方法,以使每個例項充當樹中的一個節點。

華夏公益教科書