Sunday, December 18, 2016

Rails active record migration commands I just learned!

I've been working on a side project in the last two days that's build on rails and it's been a great learning experience. Today I dealt mostly with active record migrations. Here are some that I had to use!

Adding a new table and model


> rails g model critic name:string

g is alias for generate. This command will create a model called Critic, a corresponding test, and a migration file with code for creating a new table called critics with a field named string that accepts string data types.

Adding a new table


> rails g migration CreateCritics name:string

Unlike the command above, this will only create a table.

Changing existing columns


> rails g migration ChangePosterImgSrc

This will allow you to apply any changes to columns in an existing table.

Adding new columns


Reference type

> rails g migration AddCriticToReviews critic:references
or
> rails g migration AddCriticToReviews critic:belongs_to

These also create migrations that use the change method. The only difference is that they go one step further by generating the actual addition syntax for you as well. This will generate a migration that will add a foreign key reference called critic_id to the reviews table, establishing a one to many relationship between critics and reviews.

String type

> rails g migration AddPosterImgSrcToMovies poster_img_src:string

Same as adding a reference field. Except thing time we specify a string type for the field we want to add.

Running specific migration


> rails db:migrate:up VERSION=<version_number>
> rails db:migrate:down VERSION=<version_number>

No comments:

Post a Comment