Yet Another Rails Newbie

April 25, 2006

has_one or belongs_to?

Filed under: ActiveRecord, RubyOnRails, Uncategorized — hittingthebuffers @ 9:38 am

One of the things that took a little more understanding than usual was the correct use of the ActiveRecord methods that define the relationships between your objects. I was often unsure whether to use has_one or belongs_to.

I have to write pub quizzes every so often. I had a quickly scaffolded together rails app to help me write them but it lacked all but the most basic features. So, I started a new one. I realised that I needed three tables: quizzes, questions and categories. I wrote the migrations and tried to set up the relationships in the created models. When I tried to test what I’d written in script/console. I could create quizzes and add questions to them but not assign the questions to a category. This baffled me for a while.

After going off and doing something else for a while I came back to the code and the database diagram and realised my error. While I’d correctly said that a question belonged_to a quiz, I’d not done the same with the categories and had thought that a question had a category. Looking again at the database structure I realised that the relationships work like this: The table with the foreign key in it belongs_to the table that that foreign key references. In my case my questions table had a quiz_id and a category_id. Therefore a Question has a belongs_to relationship with both the Quiz and Category models which both in turn have has_many relationships with Question.

I made the changes and it works now. It’s always good when something clicks into place.

2 Comments »

  1. [...] did some digging and found that belongs_to and has_one are commonly confused cousins.  And I found this blog post about it.  So I need to change has_one to belongs_to and I need a has_many relationship defined as [...]

    Pingback by Creating a simple one to many relationship using Ruby, ActiveRecord and MySQL | Ghost On Third — November 13, 2007 @ 5:45 am

  2. You’re right!!

    Thanks for sharing your opinion.

    Comment by Apisak S. — December 12, 2008 @ 6:56 am


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.