This is a quick trick I haven’t explored until now (no really, didn’t know it like 5 minute ago).
When you’re calling rails g model
to generate your models, you have the option to pass in the field names inline, like this:
1
|
|
The example above has something interesting: you create two columns of type integer
: role_id
and user_id
. What you really want to express, however, is that you want ot hook up two associations in your UserRole
model: belongs_to :role
and belongs_to :user
. After you generate this migration, you may have to do a couple of things by hand:
- add
add_index
commands on the migration to create the index onrole_id
anduser_id
before runningrake db:migrate
- add
belongs_to
associations inapp/models/user_role.rb
Well, all of this manual typing can be just eliminated if you use this syntax instead:
1
|
|
That’s it! We express the model with its data relations instead of raw database columns. As you can see in the generated code, rails already included the appropriate belongs_to
and indexes to the files, like below:
1 2 3 4 |
|
And to the migration file:
1 2 3 4 5 6 7 8 9 10 11 |
|
All done in a single call to rails g
. Hope you enjoy!