Click to find out more about our Work
August 24th, 2008

Tutorial : Create a blog using Ruby on Rails 2. (Part 1 – Relationships)

27 Comments

Create the Scaffolds

Step 1 : Create Directories & Configure

  1. Please create a database called blog via phpMyAdmin. If you don`t know how to go about it, please read Tutorial : Using phpMyAdmin to manage mySQL
  2. First off, Lets create a rails application called ‘blog‘. Type in the following code in your command prompt.

    rails blog -d mysql
    

    You`ll see a list of files and directories being created.

  3. Navigate to blog\config and open database.yml. Please specify the database name as blog and also enter the username and password.

    Your database.yml should look something like this.

    #if you have followed my tutorial to install php,mysql then
    #the password is root
    development:
      adapter: mysql
      encoding: utf8
      database: blog
      username: root
      password: root
      host: localhost
    
    test:
      adapter: mysql
      encoding: utf8
      database: blog
      username: root
      password: root
      host: localhost
    
    production:
      adapter: mysql
      encoding: utf8
      database: blog
      username: root
      password: root
      host: localhost
    

Step 2 : Create Scaffolds

Ok ! Now to create the scaffolds.

Scaffold :
In general terms, a scaffold refers to a temporary platform to provide support to the workers while working at heights above the ground. So Scaffold provides a temporary platform and provide support. In RoR, the same meaning holds true. We have a table, which we want to access by mapping it to a model and manipulating it through a view and corresponding controller. However, once done, we will be customizing it. For such a situation you have to use scaffolds. So, they are frameworks generated by RoR to provide access and manipulation interfaces that can be customized later.

Let’s generate scaffolds for our tables viz category and post

ruby script/generate scaffold category category_name:string

The above code creates a scaffold category with attributes
category_name – String

Lets create the next scaffold post.

ruby script/generate scaffold post post_title:string post_text:text date_of_creation:date category_id:integer

The post scaffold has 4 atttributes i.e
post_title – String
post_text – String
date_of_creation – date
category_id – integer (References Category->id)

Step 3 : Rake Database Migrate

After creating the scaffolds, lets create the database tables. No need to do any manual work here ! Type the following code to migrate everything to our database.

rake db:migrate

The above code will create the respective tables in the database, models, controllers and views.

Step 4 : Testing

Lets test our application.

Lets fire up RoR’s Server.

ruby script/server

http://localhost:3000/categories
http://localhost:3000/posts

You`ll notice that, when we are trying to create a new post, there is an extra field called Category_id. No need to worry, the kind of output we`ll be expecting is something like the image below.

New Post page on the left, Categories Page on right‘New Post’ page on the left, ‘All Categories’ Page on right

Note: Singular / Plural Concepts

For example: We created post scaffold, it can by accessed by pointing to posts.
We created a category scaffold, it can be accessed by pointing to categories.

Pages : 1 2 3

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

27 Responses to “Tutorial : Create a blog using Ruby on Rails 2. (Part 1 – Relationships)”

  1. Shailen Sobhee
    July 20, 2010 at 3:42 pm

    Why would you add category_id in the table post ? We want to make things organised and logical.

    We have the table post (id,title, text, date)
    and category (id, name)

    Then the goal is to create a table with name, say post_category linking id in post and id in category.

    What do you have to say about the above?

  2. Abder-Rahman
    July 19, 2010 at 8:53 am

    Just wanted to note a small typo here: to understand the" basic" of RoR. —> basics

    Thanks.

  3. nedia
    June 10, 2010 at 6:33 am

    Ooops! I fount some error while copying the tutorial.
    the error is like this:

    SyntaxError in PostsController#index

    /home/aiden/Desktop/blog/app/controllers/posts_controller.rb:35: syntax error, unexpected tIDENTIFIER, expecting kDO or '{' or '('
    … format.xml { render <img src="http://visionmasterdesigns.c…
    ^
    /home/aiden/Desktop/blog/app/controllers/posts_controller.rb:35: syntax error, unexpected tIDENTIFIER, expecting '}'
    …ages/smilies/icon_mad.gif" alt=":x" class="wp-smiley"> ml =>…
    ^
    /home/aiden/Desktop/blog/app/controllers/posts_controller.rb:35: syntax error, unexpected kCLASS, expecting '}'
    …s/icon_mad.gif" alt=":x" class="wp-smiley"> ml => @post }
    ^
    /home/aiden/Desktop/blog/app/controllers/posts_controller.rb:35: syntax error, unexpected tASSOC, expecting '}'
    …=":x" class="wp-smiley"> ml => @post }

    Please help!

  4. LostOne
    June 3, 2010 at 10:47 am

    you forgot login system…

  5. paylasimmerkezi
    May 7, 2010 at 11:14 am

    thank you very useful article .And this site is very good

  6. RainyD
    May 4, 2010 at 3:59 am

    This doesnt work for me at all… Keep getting NoMethodError error

  7. d1sp1n
    March 12, 2010 at 6:15 pm

    All your links come to a 'nothing found' page

  8. Adam Clarkson
    February 28, 2010 at 12:37 pm

    Hi There,

    Great tutorial, I'm just getting into Ruby on Rails and really wanted to get my own blog platform up and running asap, so this is helping loads!

    One thing I noticed, when you modify the category selection box to become an option field rather than a text box I believe you can do it with one line as follows:

    <%= f.collection_select :category_id, @cat, :id, :category_name %>

    That uses the @cat variable from the controller and handles the looping for you, I picked it up from the apple tutorials on RoR and just thought it was worth mentioning as it is a little more lightweight and elegant solution

    Moving on!
    Adam

  9. alex
    July 11, 2009 at 8:02 am

    Love the captcha!

    Anyway why is grant being an ass? If ya gunna critize it, ya gotta constructify it, brother! How should this article be better? Can you write an article for us that does this but better? Like “The best freaking article on creating categories in Ruby on Rails!!”

    I got a question though, how do I know the relationship has been formed? How do I know the project knows Posts belongs to Categories, and Categories has many Posts?

  10. Andrey
    March 31, 2009 at 9:37 pm

    Hi ! I’ve found some errors. Maybe I am wrong, but I had many errors before I noticed that closing brackets for ruby code in .erb files located behind comment sign (#), so operators were just not closed because of that. Since I moved closing brackets (“%>”) from behind the commentaries to the right part, before them, everything seem to work. Hope it will help somebody else too.
    And anyway, great tutorial!

  11. Andrey
    March 16, 2009 at 10:39 pm

    it’s just great. thanks for what you are doing. it helped me a lot.

  12. Plamen Nikolov
    March 4, 2009 at 6:53 pm

    Very useful tutorial! Thanks a lot!

  13. Manjely
    November 19, 2008 at 1:06 am

    I change the tables name but i follow all step in the tutorial, but give me this error mensage:

    NoMethodError in Checkdates#show
    Showing checkdates/show.html.erb where line #13 raised:

    undefined method `room’ for #

    Extracted source (around line #13):

    10:
    11:
    12: roomtype:
    13:
    14:
    15:
    16: Adults:

    I don’t know how to solve this problem, please who can help me!

  14. Manjely
    November 19, 2008 at 12:56 am

    I try it but give me this error
    NoMethodError in Checkdates#show
    Showing checkdates/show.html.erb where line #13 raised:

    undefined method `room’ for #

    Extracted source (around line #13):

    10:
    11:
    12: roomtype:
    13:
    14:
    15:
    16: Adults:

    Can you help me please

  15. Michael
    November 18, 2008 at 10:48 am

    @Dave Porter
    Sorry coudln`t reply earlier. Dave could you temme what the error is ? It`ll be a lil helpful for me to decipher.

  16. Dave Porter
    November 17, 2008 at 8:12 am

    Still errors in code
    ( e.g. the category loop in the new and edit views section
    cheers Dave

  17. Michael
    November 9, 2008 at 8:55 pm

    Hey Mac,
    Sorry couldn`t reply earlier.
    RoR performs all joins automatically based on the attribute we tell it to perform join on. BTW Mac please use

    [sourcecode]
    [code] -- ALL YOUR CODE HERE -- [/code]
    [/sourcecode]

    Regards

  18. Mac
    November 8, 2008 at 10:05 pm

    dude, I just posted some html in your comment block and broke it…sorry… on a more serious note, iframe/sql injections are going around these days, nasty buggers…you might want to do some input checking or at least install a picture/person verifier so bots dont inject your blog with nastiness.

  19. Mac
    November 8, 2008 at 10:01 pm

    Sure enough, I tried it and got this error…help?!
    Showing posts/index.html.erb where line #16 raised:

    You have a nil object when you didn’t expect it!
    The error occurred while evaluating nil.category_name

    Extracted source (around line #16):

    13:
    14:
    15:
    16:
    17:
    18:
    19: ‘Are you sure?’, :method => :delete %>

  20. Mac
    November 8, 2008 at 9:28 pm

    Um, could someone explain to me how index.html.erb in step 3.4 is aware of the variable @post.category.category_name? It looks like its some kind of inner join with the records in the category table… thoughts?

  21. farmer
    November 6, 2008 at 11:42 am

    Fantastic help, thanks!

  22. Mowli
    September 12, 2008 at 3:27 am

    I had to remove the comments in the changes to new.html.erb to make it work:

    Category

    <option value=”">

  23. Adam
    September 8, 2008 at 9:55 am

    Whats the schedule for this tutorials? Keep them coming!

  24. John Laudun
    September 5, 2008 at 2:17 am

    Nice write up. I used it to get up to speed on the changes in scaffold in RoR2. Thanks for that. I’m looking forward to the second part.

  25. Michael
    August 25, 2008 at 6:54 pm

    Hey grant,
    Thanks for the reply, I guess I should have taken my time in preparing this tutorial. I rushed up in a bid to finish it off fast.

    Anyways I have posted a revised version which is I hope is better than the previous version. I`ll be constantly updating it.

    Thanks for pointing out. I`ll see to it, that it won`t happen next time. This site is dedicated to provide the best content.

    Regards

  26. grant
    August 25, 2008 at 2:10 am

    Poorly formatted and lacks clear description. A tutorial should be a constructive narrative, not a terse recipe.

    My favorite bit from the tutorial is this hunk of meaninglessness: “Create some categories and then try creating posts. You`ll see that we have got our final result.”

    Yeah, you got a final result all right.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <p> <q cite=""> <strike> <strong>