Rails Generate Resource
As aspiring engineers and developers, we are constantly absorbing new and useful information. The overwhelming challenge can be sorting through all of this information and finding the important and most useful pieces of the puzzle.
Currently, I’m in Mod 2 of Flatiron School’s full-time Software Engineering program in Chicago. In less than five weeks, we have tackled Ruby on Rails and during this process I found a small piece of this puzzle to be one of the most useful —
rails g resource.
The Rails Command Line is a gateway that brings life to the foundation of an app. There are many generators and commands to use while creating new Rails apps like
rails g controller, rails g model, rails g migration, etc. All of these generators are necessary. However,
rails g resource combines them all and more!
rails g resource Model attribute_name:datatype attribute_name:datatype --no-test-framework
Generates a model (inherits from ApplicationRecord), controller (inherits from Application Controller), migration file with attributes, views folder, views helper file, and full :resources call in routes.rb file.
Option 2 — Use when creating your join model.
rails g resource Model attribute_name(default:string) model:belongs_to --no-test-framework
In addition to everything described in Option 1, this option generates foreign_key: associations in the migration file. Additionally, attribute datatypes will default to string if not specified. (Resource saving us more time)
Yes! Preventing bugs, errors and unused files or code is very smart.
rails g resource creates the core files and functions of an app including the 7 RESTful routes. With that, you can define your controller actions and model relationships, create your view files and your Rails app will be up and running!