Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Build a Todo List Application with Rails 4 Build a Todo List Application with Rails 4 Relationships

todo_item vs. todo_items

I'm a little confused about the naming of the variables in ruby. In the tutorial, in the todo_list_spec.rb, he typed in it { should have_many (:todo_items) }. Since the class is called TodoItem, shouldn't he have typed in todo_item instead of todo_items (in the plural form)? Also, I've tried both todo_item and todo_items in my own code - both seems to work? Thanks in advanced!

2 Answers

John Steer-Fowler
PLUS
John Steer-Fowler
Courses Plus Student 11,734 Points

Hey Teri,

Ruby is intelligent and can tell the difference between singular and plural. Therefore you have many items, not many item. Ruby will take :todo_items and still make the link to :todo_item unlike some other programming languages.

Brandon Barrette
Brandon Barrette
20,485 Points

In a has_many association, it has to be plural. Because a TodoList has_many todo_items (meaning more than one). Just like a TodoItem belongs_to a TodoList, we wouldn't have a TodoItem, belongs_to todo_lists. (it could belong to many, but that uses a different association.)

There is also a has_one association. Here, TodoList has_one todo_item (notice it's singular because there is only one).

You actually have to be careful when you are writing your associations. If you don't pluralize them appropriately, rails will look for an association that is not there. It will also throw an error, something like:

couldn't find the association has_many todo_item