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.