Mover ===== Move ActiveRecord records across tables like it ain't no thang. Requirements ------------
sudo gem install moverCreate the movable table ------------------------ Migration:
class CreateArticlesArchive < ActiveRecord::Migration def self.up Article.create_movable_table( :archive, :columns => %w(id title body created_at), :indexes => %w(id created_at) ) add_column :articles_archive, :move_id, :string add_column :articles_archive, :moved_at, :datetime end def self.down Article.drop_movable_table(:archive) end endThe first parameter names your movable table. In this example, the table is named
articles_archive
.
Options:
* :columns
- Only use certain columns from the original table. Defaults to all.
* :indexes
- Only create certain indexes. Defaults to all.
We also added two columns, move\_id
and moved\_at
. These are magic columns.
Define the model
----------------
class Article < ActiveRecord::Base is_movable :archive endThe
is_movable
method takes any number of parameters for multiple movable tables.
Moving records
--------------
Article.last.move_to(:archive) Article.move_to(:archive, [ "created_at > ?", Date.today ])Associations move if they are movable and if all movable tables have a
move_id
column (see magic columns).
Restoring records
-----------------
Article.move_from(:archive, [ "created_at > ?", Date.today ]) ArticleArchive.last.move_fromYou can access the movable table by prepending its name to the original class name. In this example, you would use
ArticleArchive
.
Magic columns
-------------
### move_id
By default, restoring a record will only restore itself and not its movable relationships.
To restore the relationships automatically, add the move_id
column to all movable tables involved.
### moved_at
If you need to know when the record was moved, add the moved\_at
column to your movable table.
See the create the movable table section for an example of how to add the magic columns.