Ruby On Rails Active Record gotcha
Thursday, May 11th, 2006I’ve been trying to do some Ruby On Rails development in my spare time for a personal fun project. I’ve been through almost every RoR tutorial, I’ve got the Agile Web Development with Rails book and read the majority of it, and written a very popular Ruby On Rails Cheatsheet. But every time I try to display relationship details between tables, I always got errors “undefined method“. I couldn’t see why this would work in my tutorials, but never in my own personal work. It all came down to a single letter - ’s’.
For example, if I had 2 tables; Notes and Comments with a One To Many relationship. Tables are as follows:
create table notes (
id int not null auto_increment,
body varchar(60) not null,
primary key (id)
);
create table comments (
id int not null auto_increment,
details varchar(40) not null,
note_id int not null,
primary key (id)
);
It wasn’t until I referred back to Amy Hoy’s ActiveRecord cheatsheet (Thanks Amy) that I finally found my problem. This is the one time where (my assumed) convention bit me in the ass instead of working for me. Looking back and “reading code as english” as you can commonly do with Ruby code, it makes sense.
class Note < ActiveRecord::Base
has_many :comments #note the pluralization
end
class Comment < ActiveRecord::Base
belongs_to :note #note the singular reference
end
I had previously thought the convention was that both has_many and belongs_to refered to a singular reference (comment & note). Not so. If you read the code “Comment belongs_to :note” and “Note has_many :comments” it makes perfect sense.
So in my view, I would try to reference fields like note.comment.details and get the error undefined method as the code was looking for the method note.comment instead of a related object. As soon as I fixed my model by adding the ’s’ to has_many, everything worked right away.
Newbie mistake I guess. I’m sure it won’t be the last.





