DEV Community

Samuel Lubliner
Samuel Lubliner

Posted on

Resource Generator

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

  1. 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
Enter fullscreen mode Exit fullscreen mode

Or for short,

rails g
Enter fullscreen mode Exit fullscreen mode

Example

rails generate draft:resource post title:string body:text expires_on:date board_id:integer
Enter fullscreen mode Exit fullscreen mode
  1. Migrating the database After running the generator, you must migrate the database:
rake db:migrate
Enter fullscreen mode Exit fullscreen mode

What Gets Generated?

  • Model and Migration: app/models/post.rb and db/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
Enter fullscreen mode Exit fullscreen mode

If you've migrated

rake db:rollback
rails destroy draft:resource post
Enter fullscreen mode Exit fullscreen mode

Modifying the Database Schema

Adding a Column

rails g migration AddImageToPosts
Enter fullscreen mode Exit fullscreen mode

Then in the migration file:

def change
  add_column :posts, :image, :string
end
Enter fullscreen mode Exit fullscreen mode

rake db:migrate

Removing a Column

rails g migration RemoveExpiresOnFromPosts
Enter fullscreen mode Exit fullscreen mode

Then in the migration file:

def change
  remove_column :posts, :expires_on
end
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)