DEV Community


Posted on

Work smarter, not harder (how to use the "rails g resource" command)

Ruby on Rails is a popular web application framework that simplifies web development by providing a set of conventions and tools. One of the most powerful features of Rails is the ability to generate code quickly using the built-in generators. In this blog, we will focus on the rails g resource command, which generates a set of files for a new resource in your application.

A resource in Rails is a representation of a model, controller, and views that work together to provide CRUD (Create, Read, Update, Delete) functionality for a specific type of object. For example, if you were building a blog application, you might have a resource for posts, which would include a Post model, a Posts controller, and views for displaying, editing, and creating posts.

To use the rails g resource command, you'll need to open up your terminal and navigate to the root directory of your Rails application. From there, you can run the command followed by the name of your resource, like this:

rails g resource Post
Enter fullscreen mode Exit fullscreen mode

You can also define the details of your table directly in the terminal. The type "string" is inferred, so those datatypes do not need to be defined:

rails g resource Post title content author likes:integer
Enter fullscreen mode Exit fullscreen mode

This will generate a set of files for the Post resource, including:

A migration file: This file is used to create the database table for the Post model. The migration includes columns for the various attributes of a post, such as title, content, author, and likes.

A model file: This file defines the Post class, which inherits from ActiveRecord::Base. It also includes validations and associations with other models, if applicable.

A controller file: This file defines the PostsController class, which handles HTTP requests and responses for the Post resource. It includes methods for creating, reading, updating, and deleting posts.

Views: The generator creates views for the various actions of the PostsController, such as index, show, create, update, and destroy.

A serializer file: if you have the serializer gem installed, the rails g resource command will also generate a corresponding serializer file.

Once the generator has finished running, you can run migrations to create the Post table in your database:

rails db:migrate
Enter fullscreen mode Exit fullscreen mode

And that's it! You now have a fully functional resource for Posts in your Rails application. Of course, you'll need to customize the generated files to fit your specific requirements, but this generator can save you a lot of time and effort in setting up the basic structure of your application.

Happy coding 💻

Top comments (1)

da7483 profile image
David Emmanuel

Work smarter and earn massively