[Ruby on Rails] model, controller terminal command

Overview

I have summarized the commands of model and controller that I often use. The description of "$" is omitted so that it can be copied and used. Since it is only a memo, the explanation is minimized. We will update as appropriate.

model、table

[Creation]


rails g model Post user:references body:string genre:integer

[Delete model and table]


rails destroy Post

[Delete only table]


rails g migration DropPosts

[Table name change]


rails g migration RenamePostsToBooks

column

[Add column]


rails g migration AddNameToPosts name:string price:integer
When you want to add more Add to migration file add_column :posts, :body, :text
When index is added [Singular] add_index :posts, :body, :unique => true [Multiple] add_index :posts, [:body, :price], :unique => true

[Delete column]


rails g migration RemoveNameFromPosts name:string price:integer

[Data type change]


rails g migration ChangeDataNameToPosts name:text

[Null added]


rails g migration change_column_null :posts, :body, false

[Column name change]


rails g migration RenamePriceColumnToPosts 
Add to migration file rename_column: posts,: price,: renamed column name

migration

[Execution]


rails db:migrate

[Revert to the previous version]


rails db:rollback

[Revert to the previous version]


rails db:rollback STEP=3

[Reset database information]


rails db:reset

[Reset the database and migration and migrate again]


rails db:migrate:reset

[Check migration version]


rails db:migrate:status

controller

[Create] shop is used when the directory is divided.


rails g controller shop::posts new

【Delete】


rails destroy controller shop::posts

Development environment

ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina

Recommended Posts