Let’s Make a Blog!

For many people, the one thing that really “turned them on” to Ruby on Rails was the 20-minute demo given by Rails’s creator, David Heinemeier Hansson, in which he showed how to create a simple weblog. That demo was originally done using Rails 1 and has since been updated (and changed somewhat) for Rails 2 and Rails 3. You can watch the latest demos online at http://www.rubyonrails.com/screencasts/.

A blog is a great way to show how easy it is to create a fairly complex application using Rails. In the remainder of this chapter, I’ll explain how you can create a very simple blog application. I’ll use a feature called migrations, which will cut out a lot of the hard work of creating the database structure of the Model.

Bear in mind that I have tried to keep the creation of this application as simple as possible. It is not an exact duplication of David Heinemeier Hansson’s tutorial, and it has only a subset of the features of a fully functional blog (there are no user comments and no administration interface, for example). Once you have completed my blog application, you may want to study the screencast tutorials mentioned earlier. These will show you alternative ways of producing similar results, and they will also take you further toward the creation of a more complex blog.

Note

You can compare the code of your blog application with one I created. My code is supplied in the log subdirectory of the code accompanying this chapter. This blog application is not “ready to run,” however, because it requires a database that you will have to create. You should create your own blog application by following the instructions given in the chapter. You may use the supplied code as a reference to check that the files you create match the ones I created.

Open a command prompt in the directory in which you keep your Rails applications (for example, C: ailsapps), and execute a command to create an application called Blog:

Rails 3

rails new blog

Rails 2

rails blog

Create the Database

Now let’s create a database. Here I am assuming you are using either the SQLite3 or MySQL database. As said earlier, SQLite3 is regarded as the standard database system for local development with Rails 3, and it is easier to set up and use. MySQL, on the other hand, is an industry-standard database that is more likely to be used for deployment on a website. If you are using SQLite3, you won’t need to take any special actions to create the database—Rails does it for you. You can skip straight to Scaffolding in Creating a MySQL Database. If you are using MySQL, you should follow the steps outlined in the next sections.

Creating a MySQL Database

If you are using MySQL, open a MySQL prompt by running the MySQL Command Line Client from the MySQL program group. When prompted, enter your MySQL password. Now you should see this prompt:

mysql>

Enter the following at the prompt (be sure to put the semicolon at the end):

create database blog_development;

MySQL should reply “Query OK” to confirm that the database has been created. Now ensure that your database configuration file for your Rails application contains the appropriate entries for the development database. If you are using some other database (not MySQL), your configuration entries must refer to that database.

Go to the folder in which Rails created your new blog application, and open the file database.yml in the config subdirectory. Assuming you are using MySQL, enter mysql as the adapter, localhost as the host, your MySQL username (for example, root), and your password, if you have one. The database name should match the database you just created. Here is an example (where you would enter an actual password instead of mypassword):

development:
  adapter: mysql
  host: localhost
  username: root
  database: blog_development
  password: mypassword

Note

If the server is running when you make changes to database.yml, you should restart the server afterward!

It is common to have multiple configurations—for example, for development, test, and production. For the sake of simplicity, here you will create a development configuration only; you may comment out any other entries in database.yml.

Scaffolding

You are going to use a feature called scaffolding to create a model, views, and controllers all in one go. Scaffolding is a convenient way of getting a simple application up and running quickly. Move into the new log directory, and enter the following at the system prompt:

Rails 3

rails generate scaffold post title:string body:text created_at:datetime

Rails 2

ruby script/generate scaffold post title:string body:text created_at:datetime

This tells the scaffold generator to create a model comprising Ruby code to access a database table called post with three columns, title, body, and created_at, each of which has the data type (string, text and datetime) specified after the colon. To create the database structure based on this model, you need to run a “migration” to update the database table itself.

Migration

The scaffold script has created a database migration file for you. Navigate to the dbmigrate directory. You will see that this contains a numbered migration file whose name ends with _create_posts.rb. If you open this file, you can see how the table structure is represented in Ruby code:

def self.up
    create_table :posts do |t|
        t.string :title
        t.text :body
        t.datetime :created_at

        t.timestamps
    end
end

An application may, over time, gain numerous migrations, each of which contains information on a specific iteration of the Model—changes and additions made to the table structure of the database. Experienced Rails developers can use migrations selectively to activate different versions of the Model. Here, however, you will use this migration to create the initial structure of the database.

At the system prompt in your application’s main directory (for example, /blog), you can use the rake tool to run the migration. Enter this command:

rake db:migrate

After a few moments, you should see a message stating that the rake task has completed and that CreatePosts has been migrated.

Partials

Now let’s create a new partial view template. A partial is a fragment of a web page template that Rails may insert, at runtime, into one or more complete web pages. If, for example, you plan to have the same data entry form in multiple pages on your site, you could create that form inside a partial template. The names of partial templates begin with an underscore.

Create a new file called _post.html.erb in your appviewsposts directory. Open this file, and edit its contents to match the following (or you may copy the _post.html.erb from the sample project in the source code archive):

_post.html.erb

<div>
<h2><%= link_to post.title, :action => 'show', :id => post %></h2>
<p><%= post.body %></p>
<p><small>
<%= post.created_at.to_s %>
</small></p>
</div>

Save your changes. Then open the file named show.html.erb. This file was automatically created by the scaffold script. Delete the following “boilerplate” code from the file:

<b>Title:</b>
 <%=h @post.title %>
</p>

<p>
 <b>Body:</b>
 <%=h @post.body %>
</p>

<p>
 <b>Created at:</b>
 <%=h @post.created_at %>
</p>

And replace it with this:

<%= render :partial => "post", :object => @post %>

This tells Rails to render the _post partial template at this point. The code in show.html.erb should now look like this:

<%= render :partial => "post", :object => @post %>

<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>

Test It!

And that’s it! Now you are ready to test your application. First, run the server. At the prompt in the log directory, enter this:

Rails 3

rails server

Rails 2

ruby script/server

Note

Recall that if you are not using the default port, 3000, you will need to specify the actual port number after -p as explained earlier in this chapter, for example: rails server -p3003.

Go into your web browser, and enter the following address (again, use the actual port number if this is not 3000):

http://localhost:3000/posts

You should see your page with its index page active. This is what should appear:

image with no caption

Now click the New Post link. In the New Post page, enter a title and some body text. Then click Create.

image with no caption

The next page that displays is the Show page. This is defined by the combination of the show.html.erb view and the _post.html.erb partial. Now carry on entering posts and clicking the links to navigate through the various defined views.

image with no caption

Note

As mentioned earlier, this chapter assumes you are using Rails “in the raw,” by entering all the necessary commands at the system prompt. Some IDEs provide a more integrated environment, which allows you to generate and code your application using built-in tools and utilities. You will find an overview of some Ruby and Rails IDEs in Appendix D.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.106.237