Give Us a create Method
When your application gets executed for the first time, think of how much it will help people if you have your application set up the database for them. But we have to remember that these same people will want to point that database wherever they please.
Add a create method to your application's module which builds the schema for us. The code should look like this:
require 'camping/db'
module Blog::Models
class CreateBlog < V 0.1
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
end
end
end
def Blog.create
Blog::Models.create_schema
end
Before Camping version 1.5 we didn't have nice migrations and you would have to hack it up yourself. Your PostAmble would then look like this:
#!ruby
def Blog.create
unless Blog::Models::Post.table_exists?
ActiveRecord::Schema.define do
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
end
Blog::Models::Post.reset_column_information
end
end
if __FILE__ == $0
Blog::Models::Base.establish_connection :adapter => 'sqlite3', :database => 'blog.db'
Blog::Models::Base.logger = Logger.new('camping.log')
Blog.create
puts Blog.run
end
The create method checks for the existence of the blog_posts table. If none, it creates the database.
If you use table_exists?, be sure to reset_column_information after the schema is created. Consider that when table_exists? is used, a blank schema is read as that table's column information.
In the PostAmble, the Blog.create command gets fired just before run. The commandline camping tool also fires create once before starting its request loop.
Return to CampingRulesOfThumb.
