k00k
k00k

Reputation: 17573

RoR - Foreign Keys created via associations and migrate or "by hand" (or scaffold)?

Just starting to learn Ruby on Rails. I'm using RoR 3. I have read this: http://guides.rubyonrails.org/association_basics.html

But I want to make sure I understand completely.

When creating a new model (I'm doing via scaffold for now), should I specify foreign_key fields at that point, or does the association handle that completely? I believe that association is only at app level, not at the db level, correct?

So I think I must do:

rails generate scaffold post body:text title:string user_id:integer

So in summary, when creating a blog application, must I specify the user_id field in the post model, or does the user model's has_many :posts take care of actually adding that to the db (mine is mysql) when I migrate?

And if the answer is that I should do them when I create the model in the first place (via scaffold or by hand), what happens when I decide later on that I want to add a foreign key, must I add that as an execute statement in a new migration?

Upvotes: 3

Views: 1724

Answers (1)

dwhite
dwhite

Reputation: 1988

You're correct. You need to specify the foreign key when you create your scaffold/model/migration as you stated to get the DB to be correct, and the has_many takes cares of the model for you.

So for initial generation of a scaffold (or model), just do:

rails generate scaffold post body:text title:string user_id:integer

as you stated, and add the has_many for the model itself.

For additions later on, you would make up a new migration, something like (assuming you want to use generation, but you could write your own migration):

rails generate migration add_user_id_to_posts user_id:integer

With that, you can run a rake db:migrate, and then update your model with a has_many or whatever association you need.

Upvotes: 5

Related Questions