Rails New vs Rails Generate: A Comprehensive Guide
If you‘re diving into Rails development, two commands you‘ll quickly become familiar with are rails new
and rails generate
. While they may seem similar at first glance, these commands serve distinct and important roles in the Rails ecosystem.
As a full-stack developer who has built numerous Rails applications, I can attest to the fact that understanding the difference between rails new
and rails generate
is crucial for productive Rails development. In this comprehensive guide, we‘ll dive deep into each command, looking at practical examples, best practices, and expert insights to help you master these essential tools.
The Importance of Rails New and Rails Generate
Before we get into the specifics of each command, let‘s take a step back and consider why rails new
and rails generate
are so important.
Rails is built on the principle of "convention over configuration", which means that by default, Rails makes assumptions about how you want to structure and build your application. This allows developers to write less code and focus on the unique parts of their app, rather than spending time on boilerplate setup.
The rails new
and rails generate
commands are key ways that Rails puts "convention over configuration" into practice. By providing standard application templates and component generators, these commands make it quick and easy to bootstrap a new Rails app and add new features, while maintaining a standardized structure.
Consider these statistics that highlight the popularity and importance of Rails:
- Ruby on Rails is used by over 1.2 million websites, including giants like Shopify, Airbnb, and GitHub (BuiltWith)
- Rails is the most popular web framework written in Ruby, with 60% market share (SimilarTech)
- The Rails ecosystem includes over 180,000 open source gems providing pre-built functionality (RubyGems.org)
With such a large and active community, being proficient with standard Rails tools like rails new
and rails generate
is essential for any Rails developer.
The Rails New Command
What Does Rails New Do?
At its core, the rails new
command creates a new Rails application from scratch. When you run rails new myapp
, Rails will:
- Create a new directory called
myapp
to house your application code - Set up the default Rails directory structure and files inside
myapp
- Initialize a new Git repository within the project directory
- Create configuration files for things like the database, routing, and secret credentials
- Generate a Gemfile specifying the gem dependencies for a default Rails app
- Run
bundle install
to install the default gems
After running rails new
, you‘ll have a fully functional, albeit basic, Rails application ready for development.
Options and Customization
While the default rails new
setup works great for many applications, Rails also provides a number of options to customize your new app. Some frequently used options include:
--api
: Generate an API-only application without view layer--minimal
: Generate a minimalistic Rails app without Action Cable, Action Mailer, Active Job, etc.--skip-active-record
: Use an ORM other than Active Record--database=postgresql
: Specify a database type other than the default SQLite
For example, to generate an API-only app with a PostgreSQL database, you would run:
rails new myapp --api --database=postgresql
When to Use Rails New
You should use the rails new
command when you‘re starting a brand new Rails project and need to generate the basic application structure and configuration files.
Typically, you‘ll only run rails new
once at the very beginning of a project. After that, you‘ll switch to using rails generate
to create new components within your app.
The Rails Generate Command
What Does Rails Generate Do?
While rails new
is used to create a new Rails application, rails generate
(aliased as rails g
) is used to create new components within an existing Rails application.
Some of the most commonly generated components include:
- Models: The M in MVC, used to define data objects and interact with the database
- Controllers: Handle requests, retrieve models, and prepare responses
- Migrations: Define changes to your database schema
- Mailers: Used for sending emails from your application
- Scaffolds: Quickly generate a full set of models, controllers, and views for a resource
Let‘s look at some concrete examples of using rails generate
.
Generating Models
Generating a model will create a new model file in app/models
, a new database migration in db/migrate
, and a new test file in test/models
(or spec/models
if using RSpec).
For example, to generate a User
model with a name and email field, you would run:
rails generate model User name:string email:string
This would generate the following files:
app/models/user.rb
db/migrate/TIMESTAMP_create_users.rb
test/models/user_test.rb
Generating Controllers
Generating a controller will create a new controller file in app/controllers
, view templates in app/views
, a new test file in test/controllers
, and add new routes in config/routes.rb
.
For example, to generate a PostsController
with index
, show
, new
, and create
actions, you would run:
rails generate controller Posts index show new create
This would generate the following files:
app/controllers/posts_controller.rb
app/views/posts/index.html.erb
app/views/posts/show.html.erb
app/views/posts/new.html.erb
app/views/posts/create.html.erb
test/controllers/posts_controller_test.rb
And add the following routes:
# config/routes.rb
get ‘posts/index‘
get ‘posts/show‘
get ‘posts/new‘
post ‘posts/create‘
Generating Migrations
You can generate standalone migrations to modify your database schema. For example, to add a published_at
column to the posts
table:
rails generate migration AddPublishedAtToPosts published_at:datetime
This would generate a migration file like:
# db/migrate/TIMESTAMP_add_published_at_to_posts.rb
class AddPublishedAtToPosts < ActiveRecord::Migration[6.1]
def change
add_column :posts, :published_at, :datetime
end
end
Generating Mailers
You can generate mailers to send email from your application. For example, to create a UserMailer
with a welcome_email
action:
rails generate mailer UserMailer welcome_email
This would generate:
app/mailers/user_mailer.rb
app/views/user_mailer/welcome_email.html.erb
app/views/user_mailer/welcome_email.text.erb
test/mailers/user_mailer_test.rb
Generating Scaffolds
While scaffolds aren‘t used as frequently as models or controllers on their own, they can be a useful way to quickly generate a full set of CRUD functionality for a resource:
rails generate scaffold Post title:string body:text
This would generate:
- A
Post
model and migration - A
PostsController
with full CRUD actions - View templates for each controller action
- Resource routes in
routes.rb
- Controller and model tests
Best Practices and Tips
Here are some tips and best practices for using rails generate
effectively:
- Use the singular form for model names (
User
instead ofUsers
). Rails will automatically pluralize names where needed. - For associations, use
references
instead ofbelongs_to
. For example,rails g model Comment post:references
. - Skip generating test files if you‘re using a third-party test framework like RSpec with the
--no-test-framework
option. - Customize your generators by modifying templates in
lib/templates
or creating your own generators.
The Rails Development Workflow
Understanding how rails new
and rails generate
fit into the typical Rails development workflow is key for productivity.
When starting a new Rails project, you‘ll always begin with rails new
to bootstrap your application. Then, as you build out the functionality of your app, you‘ll use rails generate
to add new models, controllers, migrations, etc. Typically, your workflow will look something like:
rails new myapp
to create a new Rails projectrails generate model ...
to create your application‘s models and database tablesrails generate controller ...
to create controllers and view templates for interacting with your modelsrails generate migration ...
for any additional changes to your database schema- Customize your models, views, controllers, and routes
- Repeat steps 2-5 to incrementally build out the features of your application
Extending the Default Generators
One powerful aspect of Rails generators is that they are fully customizable. Rails provides a number of hooks and templates you can use to modify the default generators, or even create entirely new ones.
For example, let‘s say you wanted to always use RSpec instead of Minitest as your testing framework. You could modify the default templates to use RSpec by adding the following to config/application.rb
:
config.generators do |g|
g.test_framework :rspec
end
Now, whenever you generate a new model or controller, it will automatically create RSpec spec files instead of Minitest test files.
You can also create entirely new generators. For example, maybe you frequently add a slug
field to your models for pretty URLs. You could create a custom generator to automate this:
# lib/generators/slug_migration/slug_migration_generator.rb
class SlugMigrationGenerator < Rails::Generators::Base
source_root File.expand_path(‘templates‘, __dir__)
def create_migration_file
timestamp = Time.now.strftime("%Y%m%d%H%M%S")
template "migration.rb", "db/migrate/#{timestamp}_add_slug_to_#{table_name}.rb"
end
private
def table_name
@table_name ||= ARGV[0].underscore.pluralize
end
end
You could then run rails generate slug_migration posts
to quickly generate a migration to add a slug
field to your posts
table.
Conclusion
The rails new
and rails generate
commands are two of the most fundamental tools in the Rails developer‘s toolkit. By providing standard application templates and component generators, these commands make it incredibly easy to bootstrap a new Rails app and incrementally add features while adhering to Rails conventions.
In this guide, we‘ve taken an in-depth look at how to use rails new
and rails generate
, analyzed common use cases and best practices, and even explored how to customize and extend the default generators.
Regardless of whether you‘re a seasoned Rails developer or just getting started, mastering rails new
and rails generate
is essential for productive and idiomatic Rails development. By leveraging these powerful tools, you can rapidly build robust, scalable applications while minimizing boilerplate and adhering to best practices.
So next time you‘re ready to dive into a new Rails project, remember: start with rails new
, and use rails generate
early and often. Your future self will thank you!