Ruby-on-rails – Generate model in Rails using user_id:integer vs user:references

ruby-on-rails

I'm confused on how to generate a model that belongs_to another model. My book uses this syntax to associate Micropost with User:

rails generate model Micropost user_id:integer

but https://guides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration says to do it like this:

rails generate model Micropost user:references

The migrations generated by these 2 are different. Also, for the former, how does rails know that user_id is a foreign key referencing user? Thanks!

Best Answer

Both will generate the same columns when you run the migration. In rails console, you can see that this is the case:

:001 > Micropost
=> Micropost(id: integer, user_id: integer, created_at: datetime, updated_at: datetime)

The second command adds a belongs_to :user relationship in your Micropost model whereas the first does not. When this relationship is specified, ActiveRecord will assume that the foreign key is kept in the user_id column and it will use a model named User to instantiate the specific user.

The second command also adds an index on the new user_id column.