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:
The example above has something interesting: you create two columns of type
user_id. What you really want to express, however, is that you want ot hook up two associations in your
belongs_to :role and
belongs_to :user. After you generate this migration, you may have to do a couple of things by hand:
add_indexcommands on the migration to create the index on
Well, all of this manual typing can be just eliminated if you use this syntax instead:
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!