acts_as_list.rb 2.1 KB

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