Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
More atrubyonrails.org:

The Rails Command Line

After reading this guide, you will know how to use the Rails command line:

  • To create a Rails application.
  • To generate models, controllers, tests, and database migrations.
  • To start a development server.
  • To inspect a Rails application through an interactive shell.
  • To add and edit credentials.

1. Overview

The Rails command line is a powerful part of the Ruby on Rails framework. Itallows you to quickly start a new application by generating boilerplate code(that follows Rails conventions). This guide includes an overview of Railscommands that allow you to manage all aspects of your web application, includingthe database.

You can get a list of commands available to you, which will often depend on yourcurrent directory, by typingbin/rails --help. Each command has a descriptionto help clarify what it does.

$bin/rails--helpUsage:  bin/rails COMMAND [options]You must specify a command. The most common commands are:  generate     Generate new code (short-cut alias: "g")  console      Start the Rails console (short-cut alias: "c")  server       Start the Rails server (short-cut alias: "s")  test         Run tests except system tests (short-cut alias: "t")  test:system  Run system tests  dbconsole    Start a console for the database specified in config/database.yml               (short-cut alias: "db")  plugin new   Create a new Rails railtie or engineAll commands can be run with -h (or --help) for more information.

The output ofbin/rails --help then proceeds to list all commands inalphabetical order, with a short description of each:

In addition to those commands, there are:about                              List versions of all Rails frameworks ...action_mailbox:ingress:exim        Relay an inbound email from Exim to ...action_mailbox:ingress:postfix     Relay an inbound email from Postfix ...action_mailbox:ingress:qmail       Relay an inbound email from Qmail to ...action_mailbox:install             Install Action Mailbox and its ......db:fixtures:load                   Load fixtures into the ...db:migrate                         Migrate the database ...db:migrate:status                  Display status of migrationsdb:rollback                        Roll the schema back to ......turbo:install                      Install Turbo into the appturbo:install:bun                  Install Turbo into the app with bunturbo:install:importmap            Install Turbo into the app with asset ...turbo:install:node                 Install Turbo into the app with webpackerturbo:install:redis                Switch on Redis and use it in developmentversion                            Show the Rails versionyarn:install                       Install all JavaScript dependencies as ...zeitwerk:check                     Check project structure for Zeitwerk ...

In addition tobin/rails --help, running any command from the list above withthe--help flag can also be useful. For example, you can learn about theoptions that can be used withbin/rails routes:

$bin/railsroutes--helpUsage:  bin/rails routesOptions:  -c, [--controller=CONTROLLER]      # Filter by a specific controller, e.g. PostsController or Admin::PostsController.  -g, [--grep=GREP]                  # Grep routes by a specific pattern.  -E, [--expanded], [--no-expanded]  # Print routes expanded vertically with parts explained.  -u, [--unused], [--no-unused]      # Print unused routes.List all the defined routes

Most Rails command line subcommands can be run with--help (or-h) and theoutput can be very informative. For examplebin/rails generate model --helpprints two pages of description, in addition to usage and options:

$bin/railsgenerate model--helpUsage:  bin/rails generate model NAME [field[:type][:index] field[:type][:index]] [options]Options:...Description:    Generates a new model. Pass the model name, either CamelCased or    under_scored, and an optional list of attribute pairs as arguments.    Attribute pairs are field:type arguments specifying the    model's attributes. Timestamps are added by default, so you don't have to    specify them by hand as 'created_at:datetime updated_at:datetime'.    As a special case, specifying 'password:digest' will generate a    password_digest field of string type, and configure your generated model and    tests for use with Active Model has_secure_password (assuming the default ORM and test framework are being used).    ...

Some of the most commonly used commands are:

  • bin/rails console
  • bin/rails server
  • bin/rails test
  • bin/rails generate
  • bin/rails db:migrate
  • bin/rails db:create
  • bin/rails routes
  • bin/rails dbconsole
  • rails new app_name

We'll cover the above commands (and more) in the following sections, startingwith the command for creating a new application.

2. Creating a New Rails Application

We can create a brand new Rails application using therails new command.

You will need the rails gem installed in order to run therails newcommand. You can do this by typinggem install rails - for more step-by-stepinstructions, see theInstalling Ruby on Railsguide.

With thenew command, Rails will set up the entire default directory structurealong with all the code needed to run a sample application right out of the box.The first argument torails new is the application name:

$railsnew my_app     create     create  README.md     create  Rakefile     create  config.ru     create  .gitignore     create  Gemfile     create  app     ...     create  tmp/cache     ...        run  bundle install

You can pass options to thenew command to modify its default behavior. Youcan also createapplication templatesand use them with thenew command.

2.1. Configure a Different Database

When creating a new Rails application, you can specify a preferred database foryour application by using the--database option. The default database forrails new is SQLite. For example, you can set up a PostgreSQL database likethis:

$railsnew booknotes--database=postgresql      create      create  app/controllers      create  app/helpers...

The main difference is the content of theconfig/database.yml file. With thePostgreSQL option, it looks like this:

# PostgreSQL. Versions 9.3 and up are supported.## Install the pg driver:#   gem install pg# On macOS with Homebrew:#   gem install pg -- --with-pg-config=/usr/local/bin/pg_config# On Windows:#   gem install pg#       Choose the win32 build.#       Install PostgreSQL and put its /bin directory on your path.## Configure Using Gemfile# gem "pg"#default:&defaultadapter:postgresqlencoding:unicode# For details on connection pooling, see Rails configuration guide# https://guides.rubyonrails.org/configuring.html#database-poolingpool:<%= ENV.fetch("RAILS_MAX_THREADS") { 3 } %>development:<<:*defaultdatabase:booknotes_development...

The--database=postgresql option will also modify other files generated for anew Rails app appropriately, such as adding thepg gem to theGemfile, etc.

2.2. Skipping Defaults

Therails new command by default creates dozens of files. By using the--skip option, you can skip some files from being generated if you don't needthem. For example,

$railsnew no_storage--skip-active-storageBased on the specified options, the following options will also be activated:  --skip-action-mailbox [due to --skip-active-storage]  --skip-action-text [due to --skip-active-storage]      create      create  README.md      ...

In the above example, Action Mailbox and Action Text are skipped in addition toActive Storage because they depend on Active Storage functionality.

You can get a full list of what can be skipped in the options section ofrails new --help command.

3. Starting a Rails Application Server

We can start a Rails application using thebin/rails server command, whichlaunches thePuma web server that comes bundledwith Rails. You'll use this any time you want to access your application througha web browser.

$cdmy_app$bin/railsserver=>Booting Puma=>Rails 8.1.0 application startingindevelopment=>Run`bin/railsserver--help`formore startup optionsPuma starting in single mode...* Puma version: 6.4.0 (ruby 3.1.3-p185) ("The Eagle of Durango")*  Min threads: 3*  Max threads: 3*  Environment: development*          PID: 5295* Listening on http://127.0.0.1:3000* Listening on http://[::1]:3000Use Ctrl-C to stop

With just two commands we have a Rails application up and running. Theservercommand starts the application listening on port 3000 by default. You can openyour browser tohttp://localhost:3000 to see a basicRails application running.

Most common commands have a shortcut aliases. To start the server you canuse the alias "s":bin/rails s.

You can run the application on a different port using the-p option. You canalso change the environment using-e (default isdevelopment).

$bin/railsserver-e production-p 4000

The-b option binds Rails to the specified IP address, by default it islocalhost. You can run a server as a daemon by passing a-d option.

4. Generating Code

You can use thebin/rails generate command to generate a number of differentfiles and add functionality to your application, such as models, controllers,and full scaffolds.

To see a list of built-in generators, you can runbin/rails generate (orbin/rails g for short) without any arguments. It lists all availablegenerators after the usage. You can also learn more about what a specificgenerator will do by using the--pretend option.

$bin/railsgenerateUsage:  bin/rails generate GENERATOR [args] [options]General options:  -h, [--help]     # Print generator's options and usage  -p, [--pretend]  # Run but do not make any changes  -f, [--force]    # Overwrite files that already exist  -s, [--skip]     # Skip files that already exist  -q, [--quiet]    # Suppress status outputPlease choose a generator below.Rails:  application_record  benchmark  channel  controller  generator  helper...

When you add certain gems to your application, they may install moregenerators. You can also create your own generators, see theGeneratorsguide for more information.

The purpose of Rails' built-in generators is to save you time by freeing youfrom having to write repetitive boilerplate code.

Let's add a controller with thecontroller generator.

4.1. Generating Controllers

We can find out exactly how to use thecontroller generator with thebin/rails generate controller command (which is the same as using it with--help). There is a "Usage" section and even an example:

$bin/railsgenerate controllerUsage:  bin/rails generate controller NAME [action action] [options]...Examples:    `bin/rails generate controller credit_cards open debit credit close`    This generates a `CreditCardsController` with routes like /credit_cards/debit.        Controller: app/controllers/credit_cards_controller.rb        Test:       test/controllers/credit_cards_controller_test.rb        Views:      app/views/credit_cards/debit.html.erb [...]        Helper:     app/helpers/credit_cards_helper.rb    `bin/rails generate controller users index --skip-routes`    This generates a `UsersController` with an index action and no routes.    `bin/rails generate controller admin/dashboard --parent=admin_controller`    This generates a `Admin::DashboardController` with an `AdminController` parent class.

The controller generator is expecting parameters in the form ofgeneratecontroller ControllerName action1 action2. Let's make aGreetings controllerwith an action ofhello, which will say something nice to us.

$bin/railsgenerate controller Greetings hello     create  app/controllers/greetings_controller.rb      route  get 'greetings/hello'     invoke  erb     create    app/views/greetings     create    app/views/greetings/hello.html.erb     invoke  test_unit     create    test/controllers/greetings_controller_test.rb     invoke  helper     create    app/helpers/greetings_helper.rb     invoke    test_unit

The above command created various files at specific directories. It created acontroller file, a view file, a functional test file, a helper for the view, andadded a route.

To test out the new controller, we can modify thehello action and the view todisplay a message:

classGreetingsController<ApplicationControllerdefhello@message="Hello, how are you today?"endend
<h1>A Greeting for You!</h1><p><%=@message%></p>

Then, we can start the Rails server, withbin/rails server, and go to theadded routehttp://localhost:3000/greetings/helloto see the message.

Now let's use the generator to add models to our application.

4.2. Generating Models

The Rails model generator command has a very detailed "Description" section thatis worth reading. Here is the basic usage:

$bin/railsgenerate modelUsage:  bin/rails generate model NAME [field[:type][:index] field[:type][:index]] [options]...

As an example, we can generate apost model like this:

$bin/railsgenerate model post title:string body:text    invoke  active_record    create    db/migrate/20250807202154_create_posts.rb    create    app/models/post.rb    invoke    test_unit    create      test/models/post_test.rb    create      test/fixtures/posts.yml

The model generator adds test files as well as a migration, which you'll need torun withbin/rails db:migrate.

For a list of available field types for thetype parameter, refer to theAPIdocumentation.Theindex parameter generates a corresponding index for the column. If youdon't specify a type for a field, Rails will default to typestring.

In addition to generating controllers and models separately, Rails also providesgenerators that add code for both at once as well as other files needed for astandard CRUD resource. There are two generator commands that do this:resource andscaffold. Theresource command is more lightweight thanscaffold and generates less code.

4.3. Generating Resources

Thebin/rails generate resource command generates model, migration, emptycontroller, routes, and tests. It does not generate views and it does not fillin the controller with CRUD methods.

Here are all the files generated with theresource command forpost:

$bin/railsgenerate resource post title:string body:text      invoke  active_record      create    db/migrate/20250919150856_create_posts.rb      create    app/models/post.rb      invoke    test_unit      create      test/models/post_test.rb      create      test/fixtures/posts.yml      invoke  controller      create    app/controllers/posts_controller.rb      invoke    erb      create      app/views/posts      invoke    test_unit      create      test/controllers/posts_controller_test.rb      invoke    helper      create      app/helpers/posts_helper.rb      invoke      test_unit      invoke  resource_route       route    resources :posts

Use theresource command when you don't need views (e.g. writing an API) orprefer to add controller actions manually.

4.4. Generating Scaffolds

A Rails scaffold generates a full set of files for a resource, including amodel, controller, views (HTML and JSON), routes, migration, tests, and helperfiles. It can be used for quickly prototyping CRUD interfaces or when you wantto generate the basic structure of a resource as a starting point that you cancustomize.

If you scaffold thepost resource you can see all of the files mentioned abovebeing generated:

$bin/railsgenerate scaffold post title:string body:text      invoke  active_record      create    db/migrate/20250919150748_create_posts.rb      create    app/models/post.rb      invoke    test_unit      create      test/models/post_test.rb      create      test/fixtures/posts.yml      invoke  resource_route       route    resources :posts      invoke  scaffold_controller      create    app/controllers/posts_controller.rb      invoke    erb      create      app/views/posts      create      app/views/posts/index.html.erb      create      app/views/posts/edit.html.erb      create      app/views/posts/show.html.erb      create      app/views/posts/new.html.erb      create      app/views/posts/_form.html.erb      create      app/views/posts/_post.html.erb      invoke    resource_route      invoke    test_unit      create      test/controllers/posts_controller_test.rb      create      test/system/posts_test.rb      invoke    helper      create      app/helpers/posts_helper.rb      invoke      test_unit      invoke    jbuilder      create      app/views/posts/index.json.jbuilder      create      app/views/posts/show.json.jbuilder      create      app/views/posts/_post.json.jbuilder

At this point, you can runbin/rails db:migrate to create thepost table(seeManaging the Database for more on that command).Then, if you start the Rails server withbin/rails server and navigate tohttp://localhost:3000/posts, you will be able tointeract with thepost resource - see a list of posts, create new posts, aswell as edit and delete them.

The scaffold generates test files, though you will need to modify them andactually add test cases for your code. See theTesting guide foran in-depth look at creating and running tests.

4.5. Undoing Code Generation withbin/rails destroy

Imagine you made a typing error when using thegenerate command for a model(or controller or scaffold or anything), it would be tedious to manually deleteeach file that was created by the generator. Rails provides adestroy commandfor that reason. You can think ofdestroy as the opposite ofgenerate. It'llfigure out what generate did, and undo it.

You can also use the alias "d" to invoke the destroy command:bin/rails d.

For example, if you meant to generate anarticle model but instead typedartcle:

$bin/railsgenerate model Artcle title:string body:text      invoke  active_record      create    db/migrate/20250808142940_create_artcles.rb      create    app/models/artcle.rb      invoke    test_unit      create      test/models/artcle_test.rb      create      test/fixtures/artcles.yml

You can undo thegenerate command withdestroy like this:

$bin/railsdestroy model Artcle title:string body:text      invoke  active_record      remove    db/migrate/20250808142940_create_artcles.rb      remove    app/models/artcle.rb      invoke    test_unit      remove      test/models/artcle_test.rb      remove      test/fixtures/artcles.yml

5. Interacting with a Rails Application

5.1.bin/rails console

Thebin/rails console command loads a full Rails environment (includingmodels, database, etc.) into an interactive IRB style shell. It is a powerfulfeature of the Ruby on Rails framework as it allows you to interact with, debugand explore your entire application at the command line.

The Rails Console can be useful for testing out ideas by prototyping with codeand for creating and updating records in the database without needing to use abrowser.

$bin/railsconsolemy-app(dev):001:0>Post.create(title:'First!')

The Rails Console has several useful features. For example, if you wish to testout some code without changing any data, you can usesandbox mode withbin/rails console --sandbox. Thesandbox mode wraps all database operationsin a transaction that rolls back when you exit:

$bin/railsconsole--sandboxLoading development environment in sandbox (Rails 8.1.0)Any modifications you make will be rolled back on exitmy-app(dev):001:0>

Thesandbox option is great for safely testing destructive changes withoutaffecting your database.

You can also specify the Rails environment for theconsole command with the-e option:

$bin/railsconsole-etestLoading test environment (Rails 8.1.0)

5.1.1. Theapp Object

Inside the Rails Console you have access to theapp andhelper instances.

With theapp method you can access named route helpers:

my-app(dev)>app.root_path=>"/"my-app(dev)>app.edit_user_path=>"profile/edit"

You can also use theapp object to make requests of your application withoutstarting a real server:

my-app(dev)>app.get"/",headers:{"Host"=>"localhost"}Started GET "/" for 127.0.0.1 at 2025-08-11 11:11:34 -0500...my-app(dev)>app.response.status=>200

You have to pass the "Host" header with theapp.get request above,because the Rack client used under-the-hood defaults to "www.example.com" if not"Host" is specified. You can modify your application to always uselocalhostusing a configuration or an initializer.

The reason you can "make requests" like above is because theapp object is thesame one that Rails uses for integration tests:

my-app(dev)>app.class=>ActionDispatch::Integration::Session

Theapp object exposes methods likeapp.cookies,app.session,app.post,andapp.response. This way you can simulate and debug integration tests in theRails Console.

5.1.2. Thehelper Object

Thehelper object in the Rails console is your direct portal into Rails’ viewlayer. It allows you to test out view-related formatting and utility methods inthe console, as well as custom helpers defined in your application (i.e. inapp/helpers).

my-app(dev)>helper.time_ago_in_words3.days.ago=>"3 days"my-app(dev)>helper.l(Date.today)=>"2025-08-11"my-app(dev)>helper.pluralize(3,"child")=>"3 children"my-app(dev)>helper.truncate("This is a very long sentence",length:22)=>"This is a very long..."my-app(dev)>helper.link_to("Home","/")=> "<a href=\"/\">Home</a>"

Assuming acustom_helper method is defined in aapp/helpers/*_helper.rbfile:

my-app(dev)>helper.custom_helper"testing custom_helper"

5.2.bin/rails dbconsole

Thebin/rails dbconsole command figures out which database you're using anddrops you into the command line interface appropriate for that database. It alsofigures out the command line parameters to start a session based on yourconfig/database.yml file and current Rails environment.

Once you're in adbconsole session, you can interact with your databasedirectly as you normally would. For example, if you're using PostgreSQL, runningbin/rails dbconsole may look like this:

$bin/railsdbconsolepsql (17.5 (Homebrew))Type "help" for help.booknotes_development=# helpYou are using psql, the command-line interface to PostgreSQL.Type:  \copyright for distribution terms       \h for help with SQL commands       \? for help with psql commands       \g or terminate with semicolon to execute query       \q to quitbooknotes_development=# \dt                    List of relations Schema |              Name              | Type  | Owner--------+--------------------------------+-------+------- public | action_text_rich_texts         | table | bhumi ...

Thedbconsole command is a very convenient shorthand, it's equivalent torunning thepsql command (ormysql orsqlite) with the appropriatearguments from yourdatabase.yml:

psql -h <host> -p <port> -U <username> <database_name>

So if yourdatabase.yml file looks like this:

development:adapter:postgresqldatabase:myapp_developmentusername:myuserpassword:host:localhost

Running thebin/rails dbconsole command is the same as:

psql -h localhost -U myuser myapp_development

Thedbconsole command supports MySQL (including MariaDB), PostgreSQL,and SQLite3. You can also use the alias "db" to invoke the dbconsole:bin/rails db.

If you are using multiple databases,bin/rails dbconsole will connect to theprimary database by default. You can specify which database to connect to using--database or--db:

$bin/railsdbconsole--database=animals

5.3.bin/rails runner

Therunner command executes Ruby code in the context of the Rails applicationwithout having to open a Rails Console. This can be useful for one-off tasksthat do not need the interactivity of the Rails Console. For instance:

$bin/railsrunner"puts User.count"42$bin/railsrunner'MyJob.perform_now'

You can specify the environment in which therunner command should operateusing the-e switch.

$bin/railsrunner-e production"puts User.count"

You can also execute code in a Ruby file with therunner command, in thecontext of your Rails application:

$bin/railsrunner lib/path_to_ruby_script.rb

By default,bin/rails runner scripts are automatically wrapped with the RailsExecutor (which is an instance ofActiveSupport::Executor) associated withyour Rails application. The Executor creates a “safe zone” to run arbitraryRuby inside a Rails app so that the autoloader, middleware stack, and ActiveSupport hooks all behave consistently.

Therefore, executingbin/rails runner lib/path_to_ruby_script.rb isfunctionally equivalent to the following:

Rails.application.executor.wrapdo# executes code inside lib/path_to_ruby_script.rbend

If you have a reason to opt of this behavior, there is a--skip-executoroption.

$bin/railsrunner--skip-executor lib/long_running_script.rb

5.4.bin/rails boot

Thebin/rails boot command is a low-level Rails command whose entire job is toboot your Rails application. Specifically it loadsconfig/boot.rb andconfig/application.rb files so that the application environment is ready torun.

Theboot command boots the application and exits — it does nothing else. Itcan be useful for debugging boot problems. If your app fails to start and youwant to isolate the boot phase (without running migrations, starting the server,etc.),bin/rails boot can be a simple test.

It can also be useful for timing application initialization. You can profile howlong your application takes to boot by wrappingbin/rails boot in a profiler.

6. Inspecting an Application

6.1.bin/rails routes

Thebin/rails routes command lists all defined routes in your application,including the URI Pattern and HTTP verb, as well as the Controller Action itmaps to.

$bin/railsroutes  Prefix  Verb  URI Pattern     Controller#Action  books   GET   /books(:format) books#index  books   POST  /books(:format) books#create  ...  ...

This can be useful for tracking down a routing issue, or simply getting anoverview of the resources and routes that are part of a Rails application. Youcan also narrow down the output of theroutes command with options like--controller(-c) or--grep(-g):

# Only show routes where the controller name contains "users"$bin/railsroutes--controllerusers# Show routes handled by namespace Admin::UsersController$bin/railsroutes-c admin/users# Search by name, path, or controller/action with -g (or --grep)$bin/railsroutes-gusers

There is also an option,bin/rails routes --expanded, that displays even moreinformation about each route, including the line number in yourconfig/routes.rb where that route is defined:

$bin/railsroutes--expanded--[ Route 1 ]--------------------------------------------------------------------------------Prefix            |Verb              |URI               | /assetsController#Action | Propshaft::ServerSource Location   | propshaft (1.2.1) lib/propshaft/railtie.rb:49--[ Route 2 ]--------------------------------------------------------------------------------Prefix            | aboutVerb              | GETURI               | /about(.:format)Controller#Action | posts#aboutSource Location   | /Users/bhumi/Code/try_markdown/config/routes.rb:2--[ Route 3 ]--------------------------------------------------------------------------------Prefix            | postsVerb              | GETURI               | /posts(.:format)Controller#Action | posts#indexSource Location   | /Users/bhumi/Code/try_markdown/config/routes.rb:4

In development mode, you can also access the same routes info by going tohttp://localhost:3000/rails/info/routes

6.2.bin/rails about

Thebin/rails about command displays information about your Rails application,such as Ruby, RubyGems, and Rails versions, database adapter, schema version,etc. It is useful when you need to ask for help or check if a security patchmight affect you.

$bin/railsaboutAbout your application's environmentRails version             8.1.0Ruby version              3.2.0 (x86_64-linux)RubyGems version          3.3.7Rack version              3.0.8JavaScript Runtime        Node.js (V8)Middleware:               ActionDispatch::HostAuthorization, Rack::Sendfile, ...Application root          /home/code/my_appEnvironment               developmentDatabase adapter          sqlite3Database schema version   20250205173523

6.3.bin/rails initializers

Thebin/rails initializers command prints out all defined initializers in theorder they are invoked by Rails:

$bin/railsinitializersActiveSupport::Railtie.active_support.deprecatorActionDispatch::Railtie.action_dispatch.deprecatorActiveModel::Railtie.active_model.deprecator...Booknotes::Application.set_routes_reloader_hookBooknotes::Application.set_clear_dependencies_hookBooknotes::Application.enable_yjit

This command can be useful when initializers depend on each other and the orderin which they are run matters. Using this command, you can see what's runbefore/after and discover the relationship between initializers. Rails runsframework initializers first and then application ones, defined inconfig/initializers.

6.4.bin/rails middleware

Thebin/rails middleware shows you the entire Rack middleware stack for yourRails application, in the exact order the middlewares are run for each request.

$bin/railsmiddlewareuse ActionDispatch::HostAuthorizationuse Rack::Sendfileuse ActionDispatch::Staticuse ActionDispatch::Executoruse ActionDispatch::ServerTiming...

This can be useful to see which middleware Rails includes and which ones areadded by gems (Warden::Manager from Devise) as well as for debugging andprofiling.

6.5.bin/rails stats

Thebin/rails stats command shows you things like lines of code (LOC) and thenumber of classes and methods for various components in your application.

$bin/railsstats+----------------------+--------+--------+---------+---------+-----+-------+| Name                 |  Lines |    LOC | Classes | Methods | M/C | LOC/M |+----------------------+--------+--------+---------+---------+-----+-------+| Controllers          |    309 |    247 |       7 |      37 |   5 |     4 || Helpers              |     10 |     10 |       0 |       0 |   0 |     0 || Jobs                 |      7 |      2 |       1 |       0 |   0 |     0 || Models               |     89 |     70 |       6 |       3 |   0 |    21 || Mailers              |     10 |     10 |       2 |       1 |   0 |     8 || Channels             |     16 |     14 |       1 |       2 |   2 |     5 || Views                |    622 |    501 |       0 |       1 |   0 |   499 || Stylesheets          |    584 |    495 |       0 |       0 |   0 |     0 || JavaScript           |     81 |     62 |       0 |       0 |   0 |     0 || Libraries            |      0 |      0 |       0 |       0 |   0 |     0 || Controller tests     |    117 |     75 |       4 |       9 |   2 |     6 || Helper tests         |      0 |      0 |       0 |       0 |   0 |     0 || Model tests          |     21 |      9 |       3 |       0 |   0 |     0 || Mailer tests         |      7 |      5 |       1 |       1 |   1 |     3 || Integration tests    |      0 |      0 |       0 |       0 |   0 |     0 || System tests         |     51 |     41 |       1 |       4 |   4 |     8 |+----------------------+--------+--------+---------+---------+-----+-------+| Total                |   1924 |   1541 |      26 |      58 |   2 |    24 |+----------------------+--------+--------+---------+---------+-----+-------+  Code LOC: 1411     Test LOC: 130     Code to Test Ratio: 1:0.1

6.6.bin/rails time:zones:all

Thebin/rails time:zones:all command prints the complete list of time zonesthat Active Support knows about, along with their UTC offsets followed by theRails timezone identifiers.

As an example, you can usebin/rails time:zones:local to see your system'stimezone:

$bin/rails time:zones:local* UTC -06:00 *Central AmericaCentral Time (US & Canada)ChihuahuaGuadalajaraMexico CityMonterreySaskatchewan

This can be useful when settingconfig.time_zone inconfig/application.rb,when you need an exact Rails time zone name and spelling (e.g., "Pacific Time(US & Canada)"), to validate user input or when debugging.

7. Managing Assets

Thebin/rails assets:* commands allow you to manage assets in theapp/assetsdirectory.

You can get a list of all commands in theassets: namespace like this:

$bin/rails-T assetsbin/rails assets:clean[count]  # Removes old files in config.assets.output_pathbin/rails assets:clobber       # Remove config.assets.output_pathbin/rails assets:precompile    # Compile all the assets from config.assets.pathsbin/rails assets:reveal        # Print all the assets available in config.assets.pathsbin/rails assets:reveal:full   # Print the full path of assets available in config.assets.paths

You can precompile the assets inapp/assets usingbin/railsassets:precompile. See theAsset Pipelineguide for more on precompiling.

You can remove older compiled assets usingbin/rails assets:clean. Theassets:clean command allows for rolling deploys that may still be linking toan old asset while the new assets are being built.

If you want to clearpublic/assets completely, you can usebin/rails assets:clobber.assets:clobber`.

8. Managing the Database

The commands in this section,bin/rails db:*, are all about setting updatabases, managing migrations, etc.

You can get a list of all commands in thedb: namespace like this:

$bin/rails-T dbbin/rails db:create              # Create the database from DATABASE_URL orbin/rails db:drop                # Drop the database from DATABASE_URL orbin/rails db:encryption:init     # Generate a set of keys for configuringbin/rails db:environment:set     # Set the environment value for the databasebin/rails db:fixtures:load       # Load fixtures into the current environmentsbin/rails db:migrate             # Migrate the database (options: VERSION=x,bin/rails db:migrate:down        # Run the "down" for a given migration VERSIONbin/rails db:migrate:redo        # Roll back the database one migration andbin/rails db:migrate:status      # Display status of migrationsbin/rails db:migrate:up          # Run the "up" for a given migration VERSIONbin/rails db:prepare             # Run setup if database does not exist, or runbin/rails db:reset               # Drop and recreate all databases from theirbin/rails db:rollback            # Roll the schema back to the previous versionbin/rails db:schema:cache:clear  # Clear a db/schema_cache.yml filebin/rails db:schema:cache:dump   # Create a db/schema_cache.yml filebin/rails db:schema:dump         # Create a database schema file (either db/bin/rails db:schema:load         # Load a database schema file (either db/bin/rails db:seed                # Load the seed data from db/seeds.rbbin/rails db:seed:replant        # Truncate tables of each database for currentbin/rails db:setup               # Create all databases, load all schemas, andbin/rails db:version             # Retrieve the current schema version numberbin/rails test:db                # Reset the database and run `bin/rails test`

8.1. Database Setup

Thedb:create anddb:drop commands create or delete the database for thecurrent environment (or all environments with thedb:create:all,db:drop:all)

Thedb:seed command loads sample data fromdb/seeds.rb and thedb:seed:replant command truncates tables of each database for the currentenvironment and then loads the seed data.

Thedb:setup command creates all databases, loads all schemas, and initializeswith the seed data (it does not drop databases first, like thedb:resetcommand below).

Thedb:reset command drops and recreates all databases from their schema forthe current environment and loads the seed data (so it's a combination of theabove commands).

For more on seed data, seethissection of the ActiveRecord Migrations guide.

8.2. Migrations

Thedb:migrate command is one of the most frequently run commands in a Railsapplication; it migrates the database by running all new (not yet run)migrations.

Thedb:migrate:up command runs the "up" method and thedb:migrate:downcommand runs the "down" method for the migration specified by the VERSIONargument.

$bin/railsdb:migrate:downVERSION=20250812120000

Thedb:rollback command rolls the schema back to the previous version (or youcan specify steps with theSTEP=n argument).

Thedb:migrate:redo command rolls back the database one migration andre-migrates up. It is a combination of the above two commands.

There is also adb:migrate:status command, which shows which migrations havebeen run and which are still pending:

$bin/railsdb:migrate:statusdatabase: db/development.sqlite3 Status   Migration ID    Migration Name--------------------------------------------------   up     20250101010101  Create users   up     20250102020202  Add email to users  down    20250812120000  Add age to users

Please see theMigration Guide for anexplanation of concepts related to database migrations and other migration commands.

8.3. Schema Management

There are two main commands that help with managing the database schema in yourRails application:db:schema:dump anddb:schema:load.

Thedb:schema:dump command reads your database’s current schema and writesit out to thedb/schema.rb file (ordb/structure.sql if you’ve configuredthe schema format tosql). After running migrations, Rails automatically callsschema:dump so your schema file is always up to date (and doesn't need to bemodified manually).

The schema file is a blueprint of your database and it is useful for setting upnew environments for tests or development. It’s version-controlled, so you cansee changes to the schema over time.

Thedb:schema:load command drops and recreates the database schema fromdb/schema.rb (ordb/structure.sql). It does this directly,withoutreplaying each migration one at a time.

This command is useful for quickly resetting a database to the current schemawithout running years of migrations one by one. For example, runningdb:setupalso callsdb:schema:load after creating the database and before seeding it.

You can think ofdb:schema:dump as the one thatwrites theschema.rb fileanddb:schema:load as the one thatreads that file.

8.4. Other Utility Commands

8.4.1.bin/rails db:version

Thebin/rails db:version command will show you the current version of thedatabase, which can be useful for troubleshooting.

$bin/railsdb:versiondatabase: storage/development.sqlite3Current version: 20250806173936

8.4.2.db:fixtures:load

Thedb:fixtures:load command loads fixtures into the current environment'sdatabase. To load specific fixtures, you can useFIXTURES=x,y. To load from asubdirectory intest/fixtures, useFIXTURES_DIR=z.

$bin/railsdb:fixtures:load   ->Loading fixtures fromtest/fixtures/users.yml   ->Loading fixtures fromtest/fixtures/books.yml

8.4.3.db:system:change

In an existing Rails application, it's possible to switch to a differentdatabase. Thedb:system:change command helps with that by changing theconfig/database.yml file and your database gem to the target database.

$bin/railsdb:system:change--to=postgresql    conflict  config/database.ymlOverwrite config/database.yml? (enter "h" for help) [Ynaqdhm] Y       force  config/database.yml        gsub  Gemfile        gsub  Gemfile...

8.4.4.db:encryption:init

Thedb:encryption:init command generates a set of keys for configuring ActiveRecord encryption in a given environment.

9. Running Tests

Thebin/rails test command helps you run the different types of tests in yourapplication. Thebin/rails test --help output has good examples of thedifferent options for this command:

You can run a single test by appending a line number to a filename:

  bin/rails test test/models/user_test.rb:27

You can run multiple tests within a line range by appending the line range to a filename:

  bin/rails test test/models/user_test.rb:10-20

You can run multiple files and directories at the same time:

  bin/rails test test/controllers test/integration/login_test.rb

Rails comes with a testing framework called Minitest and there are also Minitestoptions you can use with thetest command:

# Only run tests whose names match the regex /validation/$bin/rails test-n /validation/

Please see theTesting Guide for explanations andexamples of different types of tests.

10. Other Useful Commands

10.1.bin/rails notes

Thebin/rails notes command searches through your code for comments beginningwith a specific keyword. You can refer tobin/rails notes --help forinformation about usage.

By default, it will search inapp,config,db,lib, andtestdirectories for FIXME, OPTIMIZE, and TODO annotations in files with extension.builder,.rb,.rake,.yml,.yaml,.ruby,.css,.js, and.erb.

$bin/railsnotesapp/controllers/admin/users_controller.rb:  * [ 20] [TODO] any other way to do this?  * [132] [FIXME] high priority for next deploylib/school.rb:  * [ 13] [OPTIMIZE] refactor this code to make it faster

10.1.1. Annotations

You can pass specific annotations by using the-a (or--annotations) option.Note that annotations are case sensitive.

$bin/railsnotes--annotations FIXME RELEASEapp/controllers/admin/users_controller.rb:  * [101] [RELEASE] We need to look at this before next release  * [132] [FIXME] high priority for next deploylib/school.rb:  * [ 17] [FIXME]

10.1.2. Add Tags

You can add more default tags to search for by usingconfig.annotations.register_tags:

config.annotations.register_tags("DEPRECATEME","TESTME")
$bin/railsnotesapp/controllers/admin/users_controller.rb:  * [ 20] [TODO] do A/B testing on this  * [ 42] [TESTME] this needs more functional tests  * [132] [DEPRECATEME] ensure this method is deprecated in next release

10.1.3. Add Directories

You can add more default directories to search from by usingconfig.annotations.register_directories:

config.annotations.register_directories("spec","vendor")

10.1.4. Add File Extensions

You can add more default file extensions by usingconfig.annotations.register_extensions:

config.annotations.register_extensions("scss","sass"){|annotation|/\/\/\s*(#{annotation}):?\s*(.*)$/}

10.2.bin/rails tmp:

TheRails.root/tmp directory is, like the *nix /tmp directory, the holdingplace for temporary files like process id files and cached actions.

Thetmp: namespaced commands will help you clear and create theRails.root/tmp directory:

$bin/railstmp:cache:clear# clears `tmp/cache`.$bin/railstmp:sockets:clear# clears `tmp/sockets`.$bin/railstmp:screenshots:clear`# clears `tmp/screenshots`.$bin/railstmp:clear# clears all cache, sockets, and screenshot files.$bin/railstmp:create# creates tmp directories for cache, sockets, and pids.

10.3.bin/rails secret

Thebin/rails secret command generates a cryptographically secure randomstring for use as a secret key in your Rails application.

$bin/railssecret4d39f92a661b5afea8c201b0b5d797cdd3dcf8ae41a875add6ca51489b1fbbf2852a666660d32c0a09f8df863b71073ccbf7f6534162b0a690c45fd278620a63

It can be useful for setting the secret key in your application'sconfig/credentials.yml.enc file.

10.4.bin/rails credentials

Thecredentials commands provide access to encrypted credentials, so you cansafely store access tokens, database passwords, and the like inside the appwithout relying on a bunch of environment variables.

To add values to the encrypted YML fileconfig/credentials.yml.enc, you canuse thecredentials:edit command:

$bin/railscredentials:edit

This opens the decrypted credentials in an editor (set by$VISUAL or$EDITOR) for editing. When saved, the content is encrypted automatically.

You can also use the:show command to view the decrypted credential file,which may look something like this (This is from a sample application and notsensitive data):

$bin/railscredentials:show# aws:#   access_key_id: 123#   secret_access_key: 345active_record_encryption:  primary_key: 99eYu7ZO0JEwXUcpxmja5PnoRJMaazVZ  deterministic_key: lGRKzINTrMTDSuuOIr6r5kdq2sH6S6Ii  key_derivation_salt: aoOUutSgvw788fvO3z0hSgv0Bwrm76P0# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.secret_key_base: 6013280bda2fcbdbeda1732859df557a067ac81c423855aedba057f7a9b14161442d9cadfc7e48109c79143c5948de848ab5909ee54d04c34f572153466fc589

You can learn about credentials in theRails SecurityGuide.

Check out the detailed description for this command in the output ofbin/rails credentials --help.

11. Custom Rake Tasks

You may want to create custom rake tasks in your application, to delete oldrecords from the database for example. You can do this with the thebin/railsgenerate task command. Custom rake tasks have a.rake extension and areplaced in thelib/tasks folder in your Rails application. For example:

$bin/railsgenerate task coolcreate  lib/tasks/cool.rake

Thecool.rake file can contain this:

desc"I am short description for a cool task"tasktask_name:[:prerequisite_task,:another_task_we_depend_on]do# Any valid Ruby code is allowed.end

To pass arguments to your custom rake task:

task:task_name,[:arg_1]=>[:prerequisite_1,:prerequisite_2]do|task,args|argument_1=args.arg_1end

You can group tasks by placing them in namespaces:

namespace:dbdodesc"This task has something to do with the database"task:my_db_taskdo# ...endend

Invoking rake tasks looks like this:

$bin/railstask_name$bin/rails"task_name[value1]"# entire argument string should be quoted$bin/rails"task_name[value1, value2]"# separate multiple args with a comma$bin/railsdb:my_db_task

If you need to interact with your application models, perform database queries,and so on, your task can depend on theenvironment task, which will load yourRails application.

tasktask_that_requires_app_code:[:environment]doputsUser.countend


Back to top
[8]ページ先頭

©2009-2025 Movatter.jp