Rails generators quickly scaffold a database-backed web resource. Rails generators automate the creation of several files and boilerplate code for CRUD (Create, Read, Update, Delete) operations.
Steps to Generate a Resource
- Running the generator command You can create a new resource using the following command:
rails generate draft:resource <MODEL_NAME_SINGULAR> <COLUMN_1_NAME>:<COLUMN_1_DATATYPE> <COLUMN_2_NAME>:<COLUMN_2_DATATYPE> # etc
Or for short,
rails g
Example
rails generate draft:resource post title:string body:text expires_on:date board_id:integer
- Migrating the database After running the generator, you must migrate the database:
rake db:migrate
What Gets Generated?
Model and Migration:
app/models/post.rb
anddb/migrate/20200602191145_create_posts.rb
.Controller:
app/controllers/posts_controller.rb
.Views: Files within
app/views/posts
.Routes: RESTful routes added to
config/routes.rb
.
How to Correct Mistakes
If you've not migrated yet
rails destroy draft:resource post
If you've migrated
rake db:rollback
rails destroy draft:resource post
Modifying the Database Schema
Adding a Column
rails g migration AddImageToPosts
Then in the migration file:
def change
add_column :posts, :image, :string
end
rake db:migrate
Removing a Column
rails g migration RemoveExpiresOnFromPosts
Then in the migration file:
def change
remove_column :posts, :expires_on
end
rake db:migrate
If your database gets into a weird state (usually caused by deleting old migration files), your ultimate last resort is
rake db:drop
This will destroy your database and all the data within it. Next, fix migrations and re-run all from scratch with rake db:migrate
, then rake sample_data
to recover the sample data.
Top comments (0)