views:

45

answers:

1

So I just started with Rails and right now looking over HABTM. I am reading the DHH book and I see that he has two models namely article and user. They have HABTM relationships. I am wondering however whether I need to create a separate migration for the articles_users model by myself or will Rails do it for me?

If so, what happen if I create a new user and associate it with an article? Will Rails know right away what to enter inside the articles_users table?

Ex:

u = User.new(:name => "John");
a = Article.new(:title =>"Rails");

#can I do this?

a.user << u

#will rails automatically create an entry inside articles_users table?

I am somewhat confused on where Rails stop in terms of making tables for us or whatnot.

+2  A: 

You will need to manually create the table with a migration. However, most rails developers now prefer Has Many Through instead of HABTM. Another benefit is that when you generate the "join model" rails will make a migration for you!

Preston Marshall
can you give me an example of the script/generate command for the join model you just mentioned?
denniss
try: script/generate model articles_users article_id:integer user_id:integer
Brian
Brian is correct. Another advantage to using HMT is that you have an entire model that you can later add methods or more attributes for.
Preston Marshall
Sweet! Thanks guys!
denniss