Mack has changed a lot since when the original 'blog' demo tutorial was created, I thought it was time to update it to make use of all the good stuff that's been added to Mack since then. This is a great example of how the scaffold generator and migrations work. Let's dive right in, shall we?
Let's generate our Mack application, we're going to use DataMapper as our ORM, we could also use ActiveRecord:
$ mack mack_blog_2 -o data_mapper
This should produce something similar to this:
$ cd mack_blog_2
Let's fire up the server and see what we get:
$ rake server
Let's head on over to http://localhost:3000
You should see this:
That's great! That means Mack is installed and working properly! Ok, we can kill the server now so we can do a few things.
First, let's generate our scaffolding:
$ rake generate:scaffold name=post cols=title:string,email:string,body:text,created_at:date_time,updated_at:date_time
That should produce something similar to this:
Let's talk briefly about what we just did. We called the scaffold generator (rake generate:scaffold). The name=post parameter tells the generator a lot. It says that we want to create a model called, Post, a controller called 'PostsController', a series of views under app/views/posts, and a migration called <num>_create_posts.rb. Wow, that's a lot of information for one parameter! The cols parameter told the generator that we want our model to have the following columns:
- title, which is a string
- email, which is also a string
- body, which is a text blob
- created_at and updated_at, both of which are datetime fields
Armed with all that information the trusty scaffold generator goes to work building our application.
Before we can run our migrations we need to first create the database. We can do that with:
$ rake db:create:all
Now, let's migrate up the database, using our new create_posts migration so we have the posts table:
$ rake db:migrate
Now, let's fire up the server again:
$ rake server
And let's head on over to: http://localhost:3000/posts
That should give us a page that looks like this:
Now let's create a new post by clicking on the 'New Post' link:
Now, click submit and we should be taken to a page that looks something like this:
Now if we head back to http://localhost:3000/posts we should see our post:
All that's really left now is to edit our routes.rb file so people go straight to our beautiful posts index page.
Edit the following line:
r.home_page "/", :controller => :default, :action => :index
So that it looks like this:
r.home_page "/", :controller => :posts, :action => :index
That's it! How easy was that?
The full source for the demo can be found here: git://github.com/markbates/mack_blog_demo.git
Now if you're feeling crazy you can add a little XML/RSS feed to your 'blog' XML and RSS Tutorial
No comments yet