Marking Your Database Versions
Camping apps are little independent apps, often a single file, which creates the database tables and manages them without hassle, right? So what if you put out a new version of your Camping app? How do you get new tables into the database? Or, what if you need to change a field or something?
In your Models, you can have versioned classes which describe how to upgrade or downgrade the database. Here's the most common scenario:
#!ruby
module Blog::Models
class CreatePostsAndUsers < V 1.0
def self.up
create_table :blog_posts, :force => true do |t|
t.column :user_id, :integer, :null => false
t.column :title, :string, :limit => 255
t.column :body, :text
end
create_table :blog_users, :force => true do |t|
t.column :username, :string
t.column :password, :string
end
end
def self.down
drop_table :blog_posts
drop_table :blog_users
end
end
end
Apps start out with a version of 0.0. The above describes an upgrade to version 1.0, which creates the blog_users and blog_posts table. (In Camping, tables must always start with the name of your app!) I also describe a downgrade, which involves dropping both tables so I can start from scratch, if I ever want to.
Be Sure to Change Your create Method
To kick this all into gear, the create_schema method needs to be called. Put this in your create method so that the tables will get built when you start the app.
#!ruby def Blog.create Blog::Models.create_schema end
Adding the Next Version
When I release 1.1 of the blog, I should definitely add comments.
#!ruby
module Blog::Models
class CreateComments < V 1.1
def self.up
create_table :blog_comments, :force => true do |t|
t.column :post_id, :integer, :null => false
t.column :username, :string
t.column :body, :text
end
end
def self.down
drop_table :blog_comments
end
end
end
If the app is running under TheCampingServer, the above change can be saved and, when you refresh the app in your browser, the server will reload the app and update the database.
For now, Camping only uses the up method internally. The down method is only handy to you in your own scripting.
For more on how to script ActiveRecord to create and drop tables, see the section on ActiveRecord::Migration.
Return to CampingRulesOfThumb
