Mover
Move ActiveRecord records across tables like it ain't no thang.
Requirements
sudo gem install mover
Create the movable table
Migration:
class CreateArchivedArticles < ActiveRecord::Migration
def self.up
Article.create_movable_table(
:archived,
:columns => %w(id title body created_at),
:indexes => %w(id created_at)
)
add_column :archived_articles, :move_id, :string
add_column :archived_articles, :moved_at, :datetime
end
def self.down
Article.drop_movable_table(:archived)
end
end
The first parameter names your movable table. In this example, the table is named archived_articles
.
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 :archived
end
The is_movable
method takes any number of parameters for multiple movable tables.
Moving records
Article.last.move_to(:archived)
Article.move_to(:archived, [ "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(:archived, [ "created_at > ?", Date.today ])
ArchivedArticle.last.move_from
You can access the movable table by prepending its name to the original class name. In this example, you would use ArchivedArticle
.
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.