Rails generators
Asher Scott
Posted on May 23, 2022
Rails comes with many helpful ways to speedup backend development. One really convenient tool are generators.
Generators are used to quickly create your backend structure by taking care of repetitive code, allowing you to focus on the more unique aspects of your application.
There are several different things able to be created with rails generate, the most common ones you might encounter are:
rails generate
controller
migration
model
resource
scaffold
serializer
Model
rails g model <model_name>
creates a migration file, including any column names for your table if passed as an argument.
E.g. rails g model Pen brand color price:integer
would create the following migration file:
# 20220507194429_create_pens.rb
class CreatePens < ActiveRecord::Migration[6.1]
def change
create_table :pens do |t|
t.string :brand
t.string :color
t.integer :price
t.timestamps
end
end
end
model file:
# pen.rb
class Pen < ApplicationRecord
end
and spec file:
# pen_spec.rb
require 'rails_helper'
RSpec.describe Pen, type: :model do
pending "add some examples to (or delete) #{__FILE__}"
end
Resource
rails g resource Pen brand color price:integer
will create all of the above files, along with a serializer:
# pen_serializer.rb
class PenSerializer < ActiveModel::Serializer
attributes :id, :brand, :color, :price
end
controller:
# pens_controller.rb
class PensController < ApplicationController
end
your routes:
# routes.rb
Rails.application.routes.draw do
resources :pens
end
and some additional specs.
Scaffold
rails g scaffold Pen brand color price:integer
creates all of the above, but adds full CRUD capability for your controller:
# pens_controller.rb
class PensController < ApplicationController
before_action :set_pen, only: [:show, :update, :destroy]
# GET /pens
def index
@pens = Pen.all
render json: @pens
end
# GET /pens/1
def show
render json: @pen
end
# POST /pens
def create
@pen = Pen.new(pen_params)
if @pen.save
render json: @pen, status: :created, location: @pen
else
render json: @pen.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /pens/1
def update
if @pen.update(pen_params)
render json: @pen
else
render json: @pen.errors, status: :unprocessable_entity
end
end
# DELETE /pens/1
def destroy
@pen.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pen
@pen = Pen.find(params[:id])
end
# Only allow a list of trusted parameters through.
def pen_params
params.require(:pen).permit(:brand, :color, :price)
end
end
and more spec files.
Of course it's important to know how all of this code works, and why. However, once you've worked on a few rails projects, generators are a great way to quickly and painlessly create the basic framework for most applications.
Posted on May 23, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.