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.

April 23, 2006

What’s this all about then?

Filed under: Uncategorized — hittingthebuffers @ 11:15 am

Like a lot of web developers I heard about Rails last year and began to get interested it. Owning a Mac meant that it was fairly easy to get Rails installed and get up and running. Since then I’ve played with Rails but not written a full application yet. One of the problems I’ve encountered is the rather disparate nature of the documentation. So, the plan for this blog is to keep learning Rails and to document all of the useful links I find.

Blog at WordPress.com.