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

Rails Associations: has_many & belongs_to

When creating a one to many relationship in rails tutorials refer to adding both has_many in the parent of the relationship (Customer) and belongs_to in the child (Orders). Why is this?

Specifically why do you need both? Is it not possible to only use has_many and not belongs_to? Is this just for clarity?

Thanks

1 Answer

Naomi Freeman
STAFF
Naomi Freeman
Treehouse Guest Teacher

Because each model/controller is just a table, and you need space in the table for the thing you're connecting to, for the relationship to exist. You do that by adding belongs_to and has_many. There are lots of other relationships you can define:

http://guides.rubyonrails.org/association_basics.html

This is the important bit for this conversation: "In Rails, an association is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model belongs_to another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model."

A way I like to think of it is that every time you have a belongs_to or has_many, it gives your table either a key or a keyhole. Some keys are universal. Some are only good for one particular thing. And if the keyhole is 'polymorphic', it can accept a few different assigned keys.

I learned about relationships and how they appear in tables by doing Rails for Zombies. I love Treehouse! It is amazing! I love that learning one language is supported by learning other languages and design and so many important things. And relationships baffled me for a long time. I kept breaking my apps because I wasn't defining things right. I just couldn't see it.

Another way to see this is to check out your db - schema.rb. Just generate some random relationships and see how it changes it. You can also set this up by using references in the command line/terminal as you're generating things.

The schema file shows you what is in your table. Each line is a cell. The relationship needs a cell to exist in.

Hopefully one part of what I've said points you in the right direction to understanding relationships better :)