acts_as_list.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #---
  2. # Excerpted from "Agile Web Development with Rails",
  3. # published by The Pragmatic Bookshelf.
  4. # Copyrights apply to this code. It may not be used to create training material,
  5. # courses, books, articles, and the like. Contact us if you are in doubt.
  6. # We make no guarantees that this code is fit for any purpose.
  7. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. #---
  9. $: << File.dirname(__FILE__)
  10. require "connect"
  11. require "logger"
  12. require "rubygems"
  13. require "active_record"
  14. require "./vendor/plugins/acts_as_list/init"
  15. #ActiveRecord::Base.logger = Logger.new(STDERR)
  16. ActiveRecord::Base.connection.instance_eval do
  17. create_table :parents, :force => true do |t|
  18. end
  19. create_table :children, :force => true do |t|
  20. t.integer :parent_id
  21. t.string :name
  22. t.integer :position
  23. end
  24. end
  25. class Parent < ActiveRecord::Base
  26. has_many :children, :order => :position
  27. end
  28. class Child < ActiveRecord::Base
  29. belongs_to :parent
  30. acts_as_list :scope => :parent
  31. end
  32. parent = Parent.create
  33. %w{ One Two Three Four}.each do |name|
  34. parent.children.create(:name => name)
  35. end
  36. parent.save
  37. def display_children(parent)
  38. puts parent.children(true).map {|child| child.name }.join(", ")
  39. end
  40. display_children(parent) #=> One, Two, Three, Four
  41. puts parent.children[0].first? #=> true
  42. two = parent.children[1]
  43. puts two.lower_item.name #=> Three
  44. puts two.higher_item.name #=> One
  45. parent.children[0].move_lower
  46. display_children(parent) #=> Two, One, Three, Four
  47. parent.children[2].move_to_top
  48. display_children(parent) #=> Three, Two, One, Four
  49. parent.children[2].destroy
  50. display_children(parent) #=> Three, Two, Four