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

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

30 Comments

Hello !
Its been a long time since my last post. I have been hell busy this week, barely had time to update. This is the revised version.

This tutorial will form the base for the upcoming series of tutorials on how to create a simple blog application in Ruby on Rails(RoR).
Part 1 will discuss about how relationships are defined in RoR and the basics as usual ;)

Index

Introduction

Let me explain what we are trying to create. We will be creating our own very simple blog application using Ruby on Rails. The blog will have

  • A Simple Login System
  • A Simple Administrative Interface to manage posts,categories and comments
  • Display comments for every post
  • Ajax Implementation

What all you`ll learn :

  • To create and work with scaffolds
  • Relationships in Rails
  • Migrations
  • How Models, Controllers and Views work
  • A simple login system
  • Ajax Implementation in this blog

A lot more as we go on … ;)

Some Conventions in Rails

  • The name of the table must be in its plural form: By default everytime we create a scaffold, the table created will be of its pluralized form. Rails will derive the singular name for the corresponding class automatically.
    For Example. If we create a scaffold called category, Rails will automatically derive its plural form i.e categories.
  • By default primary key called id will be created for every scaffold even if not specified. The Data type of the Primary key should be Integer.
  • The Foreign keys should be named ‘table name of the referenced table + _id’
    For Example : if we want to use Table-Category’s Primary key ‘id’, we`ll create a attribute called category_id in our ‘posts’ table.

What are we doing in Part 1 ?

In this tutorial (Part 1 of the Series) we`ll learn how to create different categories and assign our posts to these categories. Every post will show which category it belongs to.

So to achieve this, we need 2 tables. The database schema for the same will be something like

category(id,category_name)
post(id,post_title,post_text,date_of_creation,category_id)

The schema is pretty self explainatory. category_id of ‘post’ is the attribute which will contain the id of ‘category’. The simplest way to put this is, every record inside the post table will contain category_id which will help us retrieve the category_name by referring to the other table i.e category.

Pre-requistes :

I would really suggest you people to read the following tutorials, to understand the basic of RoR.

Pages : 1 2 3

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

  1. Shailen Sobhee
    July 20, 2010 at 9:12 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?

    • rowoot
      August 3, 2010 at 7:03 am

      Hi Shailen,

      I wrote the post with the assumption that, only one category will be assigned to one post (one post to one cat), that is the reason I went with the above db schema.
      Your db logic allows the post to have multiple categories, which is very valid. (Many to Many).

  2. Abder-Rahman
    July 19, 2010 at 2:23 pm

    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!

    • Ricardo Souza
      August 30, 2010 at 7:15 am

      Hi nedia, how did you solved your problem ? I'm getting the same error…

      syntax error, unexpected tIDENTIFIER, expecting

      I think it's something related to format.xml + render img…

  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>