更多内容请访问 rubyonrails.org:

1. 概述

Rails 命令行是 Ruby on Rails 框架的强大组成部分。它允许您通过生成样板代码(遵循 Rails 约定)快速启动新应用程序。本指南包括 Rails 命令的概述,这些命令允许您管理 Web 应用程序的所有方面,包括数据库。

您可以通过键入 bin/rails --help 获取可用命令列表,这通常取决于您当前的目录。每个命令都有一个描述,以帮助阐明其功能。

$ bin/rails --help
Usage:
  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 engine

All commands can be run with -h (or --help) for more information.

bin/rails --help 的输出然后按字母顺序列出所有命令,并附有每个命令的简短描述。

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 migrations
db:rollback                        Roll the schema back to ...
...
turbo:install                      Install Turbo into the app
turbo:install:bun                  Install Turbo into the app with bun
turbo:install:importmap            Install Turbo into the app with asset ...
turbo:install:node                 Install Turbo into the app with webpacker
turbo:install:redis                Switch on Redis and use it in development
version                            Show the Rails version
yarn:install                       Install all JavaScript dependencies as ...
zeitwerk:check                     Check project structure for Zeitwerk ...

除了 bin/rails --help 之外,使用 --help 标志运行上述列表中的任何命令也很有用。例如,您可以了解可与 bin/rails routes 一起使用的选项。

$ bin/rails routes --help
Usage:
  bin/rails routes

Options:
  -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

大多数 Rails 命令行子命令都可以使用 --help(或 -h)运行,并且输出信息量很大。例如,bin/rails generate model --help 会打印两页的描述,此外还有用法和选项。

$ bin/rails generate model --help
Usage:
  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).
    ...

一些最常用的命令是

  • 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

我们将在以下章节中介绍上述命令(以及更多命令),从创建新应用程序的命令开始。

2. 创建新的 Rails 应用程序

我们可以使用 rails new 命令创建一个全新的 Rails 应用程序。

您需要安装 rails gem 才能运行 rails new 命令。您可以通过键入 gem install rails 来完成此操作 - 有关更多分步说明,请参阅安装 Ruby on Rails 指南。

使用 new 命令,Rails 将设置整个默认目录结构以及运行开箱即用示例应用程序所需的所有代码。rails new 的第一个参数是应用程序名称。

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

您可以将选项传递给 new 命令以修改其默认行为。您还可以创建应用程序模板并将其与 new 命令一起使用。

2.1. 配置不同的数据库

创建新的 Rails 应用程序时,您可以使用 --database 选项为您的应用程序指定首选数据库。rails new 的默认数据库是 SQLite。例如,您可以像这样设置 PostgreSQL 数据库

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

主要区别在于 config/database.yml 文件的内容。使用 PostgreSQL 选项,它看起来像这样

# 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: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.cn/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 3 } %>


development:
  <<: *default
  database: booknotes_development
  ...

--database=postgresql 选项还会相应地修改为新 Rails 应用程序生成的其他文件,例如将 pg gem 添加到 Gemfile 等。

2.2. 跳过默认设置

rails new 命令默认创建数十个文件。通过使用 --skip 选项,如果您不需要某些文件,可以跳过它们的生成。例如,

$ rails new no_storage --skip-active-storage
Based 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
      ...

在上面的示例中,Action Mailbox 和 Action Text 以及 Active Storage 被跳过,因为它们依赖于 Active Storage 功能。

您可以在 rails new --help 命令的选项部分获取可以跳过的完整列表。

3. 启动 Rails 应用程序服务器

我们可以使用 bin/rails server 命令启动 Rails 应用程序,该命令启动与 Rails 捆绑在一起的 Puma Web 服务器。任何时候您想通过 Web 浏览器访问您的应用程序时,都会使用它。

$ cd my_app
$ bin/rails server
=> Booting Puma
=> Rails 8.1.0 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma 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]:3000
Use Ctrl-C to stop

只需两个命令,我们的 Rails 应用程序就启动并运行了。server 命令默认在端口 3000 上启动应用程序侦听。您可以在浏览器中打开 https://:3000 以查看正在运行的基本 Rails 应用程序。

大多数常用命令都有快捷别名。要启动服务器,您可以使用别名“s”:bin/rails s

您可以使用 -p 选项在不同的端口上运行应用程序。您还可以使用 -e 更改环境(默认为 development)。

$ bin/rails server -e production -p 4000

-b 选项将 Rails 绑定到指定的 IP 地址,默认是 localhost。您可以通过传递 -d 选项将服务器作为守护进程运行。

4. 生成代码

您可以使用 bin/rails generate 命令生成许多不同的文件并向您的应用程序添加功能,例如模型、控制器和完整的脚手架。

要查看内置生成器列表,您可以运行不带任何参数的 bin/rails generate(或简写 bin/rails g)。它在用法之后列出所有可用的生成器。您还可以通过使用 --pretend 选项了解特定生成器将做什么。

$ bin/rails generate
Usage:
  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 output

Please choose a generator below.
Rails:
  application_record
  benchmark
  channel
  controller
  generator
  helper
...

当您向应用程序添加某些 gem 时,它们可能会安装更多生成器。您还可以创建自己的生成器,有关更多信息,请参阅生成器指南

Rails 内置生成器的目的是通过让您免于编写重复的样板代码来节省您的时间。

让我们使用 controller 生成器添加一个控制器。

4.1. 生成控制器

我们可以使用 bin/rails generate controller 命令(与使用 --help 相同)确切地了解如何使用 controller 生成器。有一个“用法”部分甚至一个示例

$ bin/rails generate controller
Usage:
  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.

控制器生成器期望参数的形式为 generate controller ControllerName action1 action2。让我们创建一个包含 hello 动作的 Greetings 控制器,它会向我们问好。

$ bin/rails generate 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

上述命令在特定目录中创建了各种文件。它创建了一个控制器文件、一个视图文件、一个功能测试文件、一个视图助手,并添加了一个路由。

要测试新控制器,我们可以修改 hello 动作和视图以显示消息

class GreetingsController < ApplicationController
  def hello
    @message = "Hello, how are you today?"
  end
end
<h1>A Greeting for You!</h1>
<p><%= @message %></p>

然后,我们可以使用 bin/rails server 启动 Rails 服务器,并访问添加的路由 https://:3000/greetings/hello 以查看消息。

现在让我们使用生成器将模型添加到我们的应用程序。

4.2. 生成模型

Rails 模型生成器命令有一个非常详细的“描述”部分,值得一读。这是基本用法

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

例如,我们可以像这样生成一个 post 模型

$ bin/rails generate 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

模型生成器添加测试文件以及迁移,您需要使用 bin/rails db:migrate 运行。

有关 type 参数的可用字段类型列表,请参阅API 文档index 参数为列生成相应的索引。如果您未指定字段的类型,Rails 将默认为类型 string

除了单独生成控制器和模型之外,Rails 还提供了生成器,可以同时添加两者的代码以及标准 CRUD 资源所需的其他文件。有两个生成器命令可以做到这一点:resourcescaffoldresource 命令比 scaffold 更轻量级,生成的代码更少。

4.3. 生成资源

bin/rails generate resource 命令生成模型、迁移、空控制器、路由和测试。它不生成视图,也不使用 CRUD 方法填充控制器。

这是使用 resource 命令为 post 生成的所有文件

$ bin/rails generate 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

当您不需要视图(例如编写 API)或喜欢手动添加控制器动作时,请使用 resource 命令。

4.4. 生成脚手架

Rails 脚手架为资源生成一整套文件,包括模型、控制器、视图(HTML 和 JSON)、路由、迁移、测试和助手文件。它可用于快速原型化 CRUD 接口,或者当您想生成资源的基本结构作为可以自定义的起点时。

如果您为 post 资源搭建脚手架,您可以看到所有上述文件都被生成

$ bin/rails generate 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

此时,您可以运行 bin/rails db:migrate 来创建 post 表(有关该命令的更多信息,请参阅管理数据库)。然后,如果您使用 bin/rails server 启动 Rails 服务器并导航到 https://:3000/posts,您将能够与 post 资源交互 - 查看帖子列表、创建新帖子以及编辑和删除它们。

脚手架会生成测试文件,但您需要修改它们并实际为您的代码添加测试用例。有关创建和运行测试的深入了解,请参阅测试指南

4.5. 使用 bin/rails destroy 撤销代码生成

想象一下,您在使用 generate 命令生成模型(或控制器或脚手架或任何其他东西)时打错了字,手动删除生成器创建的每个文件将是繁琐的。Rails 为此提供了 destroy 命令。您可以将 destroy 视为 generate 的反义词。它会弄清楚 generate 做了什么,然后撤销它。

您也可以使用别名“d”来调用 destroy 命令:bin/rails d。d`。

例如,如果您想生成一个 article 模型但输入了 artcle

$ bin/rails generate 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

您可以使用 destroy 撤销 generate 命令,如下所示

$ bin/rails destroy 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. 与 Rails 应用程序交互

5.1. bin/rails console

bin/rails console 命令将完整的 Rails 环境(包括模型、数据库等)加载到交互式 IRB 样式 shell 中。它是 Ruby on Rails 框架的一个强大功能,因为它允许您在命令行与整个应用程序交互、调试和探索。

Rails 控制台对于通过代码原型设计来测试想法以及在不需要使用浏览器的情况下创建和更新数据库中的记录非常有用。

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

Rails 控制台具有几个有用的功能。例如,如果您希望测试一些代码而不更改任何数据,您可以使用 bin/rails console --sandbox 启用 sandbox 模式。sandbox 模式将所有数据库操作包装在一个事务中,该事务在您退出时回滚

$ bin/rails console --sandbox
Loading development environment in sandbox (Rails 8.1.0)
Any modifications you make will be rolled back on exit
my-app(dev):001:0>

sandbox 选项非常适合安全地测试破坏性更改而不会影响您的数据库。

您还可以使用 -e 选项为 console 命令指定 Rails 环境

$ bin/rails console -e test
Loading test environment (Rails 8.1.0)

5.1.1. app 对象

在 Rails 控制台中,您可以访问 apphelper 实例。

使用 app 方法可以访问命名路由助手

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

您还可以使用 app 对象向您的应用程序发出请求,而无需启动真正的服务器

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

您必须在上面的 app.get 请求中传递“Host”头,因为如果没有指定“Host”,底层使用的 Rack 客户端默认使用“www.example.com”。您可以通过配置或初始化器修改您的应用程序,使其始终使用 localhost

您之所以可以像上面那样“发出请求”,是因为 app 对象与 Rails 用于集成测试的对象相同

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

app 对象暴露了诸如 app.cookiesapp.sessionapp.postapp.response 等方法。这样您就可以在 Rails 控制台中模拟和调试集成测试。

5.1.2. helper 对象

Rails 控制台中的 helper 对象是您直接进入 Rails 视图层的门户。它允许您在控制台中测试与视图相关的格式化和实用方法,以及在您的应用程序中定义(即在 app/helpers 中)的自定义助手。

my-app(dev)> helper.time_ago_in_words 3.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>"

假设在 app/helpers/*_helper.rb 文件中定义了一个 custom_helper 方法

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

5.2. bin/rails dbconsole

bin/rails dbconsole 命令会找出您正在使用的数据库,并将其带入适合该数据库的命令行界面。它还会根据您的 config/database.yml 文件和当前 Rails 环境找出启动会话的命令行参数。

进入 dbconsole 会话后,您可以像往常一样直接与数据库交互。例如,如果您正在使用 PostgreSQL,运行 bin/rails dbconsole 可能看起来像这样

$ bin/rails dbconsole
psql (17.5 (Homebrew))
Type "help" for help.

booknotes_development=# help
You 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 quit
booknotes_development=# \dt
                    List of relations
 Schema |              Name              | Type  | Owner
--------+--------------------------------+-------+-------
 public | action_text_rich_texts         | table | bhumi
 ...

dbconsole 命令是一个非常方便的简写,它等同于运行 psql 命令(或 mysqlsqlite)并带上 database.yml 中的适当参数

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

因此,如果您的 database.yml 文件看起来像这样

development:
  adapter: postgresql
  database: myapp_development
  username: myuser
  password:
  host: localhost

运行 bin/rails dbconsole 命令与以下命令相同

psql -h localhost -U myuser myapp_development

dbconsole 命令支持 MySQL(包括 MariaDB)、PostgreSQL 和 SQLite3。您也可以使用别名“db”来调用 dbconsole:bin/rails db

如果您使用多个数据库,bin/rails dbconsole 默认会连接到主数据库。您可以使用 --database--db 指定要连接的数据库。

$ bin/rails dbconsole --database=animals

5.3. bin/rails runner

runner 命令在 Rails 应用程序的上下文中执行 Ruby 代码,而无需打开 Rails Console。这对于不需要 Rails Console 交互性的单次任务非常有用。例如

$ bin/rails runner "puts User.count"
42

$ bin/rails runner 'MyJob.perform_now'

您可以使用 -e 开关指定 runner 命令应在其中运行的环境。

$ bin/rails runner -e production "puts User.count"

您还可以使用 runner 命令在 Rails 应用程序的上下文中执行 Ruby 文件中的代码

$ bin/rails runner lib/path_to_ruby_script.rb

默认情况下,bin/rails runner 脚本会自动用 Rails 执行器(它是与您的 Rails 应用程序关联的 ActiveSupport::Executor 实例)包装。执行器创建了一个“安全区”来在 Rails 应用程序内运行任意 Ruby,以便自动加载器、中间件栈和 Active Support 钩子都能保持一致。

因此,执行 bin/rails runner lib/path_to_ruby_script.rb 在功能上等同于以下内容

Rails.application.executor.wrap do
  # executes code inside lib/path_to_ruby_script.rb
end

如果您有理由选择不使用此行为,则可以使用 --skip-executor 选项。

$ bin/rails runner --skip-executor lib/long_running_script.rb

5.4. bin/rails boot

bin/rails boot 命令是一个低级 Rails 命令,其全部工作是启动您的 Rails 应用程序。具体来说,它加载 config/boot.rbconfig/application.rb 文件,以便应用程序环境准备好运行。

boot 命令启动应用程序并退出——它不做任何其他事情。它可能对调试启动问题很有用。如果您的应用程序无法启动,并且您想隔离启动阶段(而不运行迁移、启动服务器等),bin/rails boot 可以是一个简单的测试。

它对于计时应用程序初始化也很有用。您可以通过在分析器中包装 bin/rails boot 来分析应用程序启动需要多长时间。

6. 检查应用程序

6.1. bin/rails routes

bin/rails routes 命令列出应用程序中所有定义的路由,包括 URI 模式和 HTTP 动词,以及它映射到的控制器动作。

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

这对于跟踪路由问题或简单地获取 Rails 应用程序中的资源和路由概览非常有用。您还可以使用 --controller(-c)--grep(-g) 等选项缩小 routes 命令的输出范围。

# Only show routes where the controller name contains "users"
$ bin/rails routes --controller users

# Show routes handled by namespace Admin::UsersController
$ bin/rails routes -c admin/users

# Search by name, path, or controller/action with -g (or --grep)
$ bin/rails routes -g users

还有一个选项 bin/rails routes --expanded,它显示每个路由的更多信息,包括您的 config/routes.rb 中定义该路由的行号。

$ bin/rails routes --expanded
--[ Route 1 ]--------------------------------------------------------------------------------
Prefix            |
Verb              |
URI               | /assets
Controller#Action | Propshaft::Server
Source Location   | propshaft (1.2.1) lib/propshaft/railtie.rb:49
--[ Route 2 ]--------------------------------------------------------------------------------
Prefix            | about
Verb              | GET
URI               | /about(.:format)
Controller#Action | posts#about
Source Location   | /Users/bhumi/Code/try_markdown/config/routes.rb:2
--[ Route 3 ]--------------------------------------------------------------------------------
Prefix            | posts
Verb              | GET
URI               | /posts(.:format)
Controller#Action | posts#index
Source Location   | /Users/bhumi/Code/try_markdown/config/routes.rb:4

在开发模式下,您还可以通过访问 https://:3000/rails/info/routes 来获取相同的路由信息。

6.2. bin/rails about

bin/rails about 命令显示有关您的 Rails 应用程序的信息,例如 Ruby、RubyGems 和 Rails 版本、数据库适配器、模式版本等。当您需要寻求帮助或检查安全补丁是否可能影响您时,它很有用。

$ bin/rails about
About your application's environment
Rails version             8.1.0
Ruby version              3.2.0 (x86_64-linux)
RubyGems version          3.3.7
Rack version              3.0.8
JavaScript Runtime        Node.js (V8)
Middleware:               ActionDispatch::HostAuthorization, Rack::Sendfile, ...
Application root          /home/code/my_app
Environment               development
Database adapter          sqlite3
Database schema version   20250205173523

6.3. bin/rails initializers

bin/rails initializers 命令打印出 Rails 按照调用顺序定义的所有初始化器

$ bin/rails initializers
ActiveSupport::Railtie.active_support.deprecator
ActionDispatch::Railtie.action_dispatch.deprecator
ActiveModel::Railtie.active_model.deprecator
...
Booknotes::Application.set_routes_reloader_hook
Booknotes::Application.set_clear_dependencies_hook
Booknotes::Application.enable_yjit

当初始化器相互依赖且运行顺序很重要时,此命令会很有用。使用此命令,您可以查看哪些在之前/之后运行,并发现初始化器之间的关系。Rails 首先运行框架初始化器,然后运行在 config/initializers 中定义的应用程序初始化器。

6.4. bin/rails middleware

bin/rails middleware 向您显示您的 Rails 应用程序的整个 Rack 中间件栈,中间件按每个请求运行的确切顺序排列。

$ bin/rails middleware
use ActionDispatch::HostAuthorization
use Rack::Sendfile
use ActionDispatch::Static
use ActionDispatch::Executor
use ActionDispatch::ServerTiming
...

这对于查看 Rails 包含哪些中间件以及 gem(来自 Devise 的 Warden::Manager)添加了哪些中间件非常有用,也适用于调试和性能分析。

6.5. bin/rails stats

bin/rails stats 命令显示您的应用程序中各种组件的代码行数(LOC)以及类和方法的数量等信息。

$ bin/rails stats
+----------------------+--------+--------+---------+---------+-----+-------+
| 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

bin/rails time:zones:all 命令打印 Active Support 已知的所有时区完整列表,以及它们的 UTC 偏移量和 Rails 时区标识符。

例如,您可以使用 bin/rails time:zones:local 来查看您的系统时区

$ bin/rails time:zones:local

* UTC -06:00 *
Central America
Central Time (US & Canada)
Chihuahua
Guadalajara
Mexico City
Monterrey
Saskatchewan

当您需要在 config/application.rb 中设置 config.time_zone 时,当您需要确切的 Rails 时区名称和拼写(例如,“太平洋时间(美国和加拿大)”)时,验证用户输入或调试时,这会很有用。

7. 管理资产

bin/rails assets:* 命令允许您管理 app/assets 目录中的资产。

您可以像这样获取 assets: 命名空间中所有命令的列表

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

您可以使用 bin/rails assets:precompile 预编译 app/assets 中的资产。有关预编译的更多信息,请参阅资产管道指南

您可以使用 bin/rails assets:clean 删除旧的已编译资产。assets:clean 命令允许进行滚动部署,这些部署可能仍链接到旧资产,而新资产正在构建中。

如果您想完全清除 public/assets,可以使用 bin/rails assets:clobber。assets:clobber`。

8. 管理数据库

本节中的命令 bin/rails db:* 都与设置数据库、管理迁移等有关。

您可以像这样获取 db: 命名空间中所有命令的列表

$ bin/rails -T db
bin/rails db:create              # Create the database from DATABASE_URL or
bin/rails db:drop                # Drop the database from DATABASE_URL or
bin/rails db:encryption:init     # Generate a set of keys for configuring
bin/rails db:environment:set     # Set the environment value for the database
bin/rails db:fixtures:load       # Load fixtures into the current environments
bin/rails db:migrate             # Migrate the database (options: VERSION=x,
bin/rails db:migrate:down        # Run the "down" for a given migration VERSION
bin/rails db:migrate:redo        # Roll back the database one migration and
bin/rails db:migrate:status      # Display status of migrations
bin/rails db:migrate:up          # Run the "up" for a given migration VERSION
bin/rails db:prepare             # Run setup if database does not exist, or run
bin/rails db:reset               # Drop and recreate all databases from their
bin/rails db:rollback            # Roll the schema back to the previous version
bin/rails db:schema:cache:clear  # Clear a db/schema_cache.yml file
bin/rails db:schema:cache:dump   # Create a db/schema_cache.yml file
bin/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.rb
bin/rails db:seed:replant        # Truncate tables of each database for current
bin/rails db:setup               # Create all databases, load all schemas, and
bin/rails db:version             # Retrieve the current schema version number
bin/rails test:db                # Reset the database and run `bin/rails test`

8.1. 数据库设置

db:createdb:drop 命令为当前环境(或所有环境,使用 db:create:alldb:drop:all)创建或删除数据库。

db:seed 命令从 db/seeds.rb 加载示例数据,db:seed:replant 命令截断当前环境的每个数据库的表,然后加载种子数据。

db:setup 命令创建所有数据库,加载所有模式,并使用种子数据进行初始化(它不像下面的 db:reset 命令那样首先删除数据库)。

db:reset 命令删除并从当前环境的模式重新创建所有数据库,并加载种子数据(因此它是上述命令的组合)。

有关种子数据的更多信息,请参阅 Active Record Migrations 指南的此部分

8.2. 迁移

db:migrate 命令是 Rails 应用程序中最常运行的命令之一;它通过运行所有新的(尚未运行的)迁移来迁移数据库。

db:migrate:up 命令运行指定版本参数的迁移的“up”方法,db:migrate:down 命令运行指定版本参数的迁移的“down”方法。

$ bin/rails db:migrate:down VERSION=20250812120000

db:rollback 命令将模式回滚到上一个版本(或者您可以使用 STEP=n 参数指定步骤)。

db:migrate:redo 命令将数据库回滚一个迁移并重新向上迁移。它是上述两个命令的组合。

还有一个 db:migrate:status 命令,它显示哪些迁移已运行,哪些仍在待处理中

$ bin/rails db:migrate:status
database: db/development.sqlite3

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20250101010101  Create users
   up     20250102020202  Add email to users
  down    20250812120000  Add age to users

请参阅迁移指南,了解与数据库迁移和其他迁移命令相关的概念。

8.3. 模式管理

在 Rails 应用程序中,有两个主要的命令有助于管理数据库模式:db:schema:dumpdb:schema:load

db:schema:dump 命令读取您数据库的当前模式并将其写入 db/schema.rb 文件(如果您已将模式格式配置为 sql,则写入 db/structure.sql)。运行迁移后,Rails 会自动调用 schema:dump,因此您的模式文件始终是最新的(并且不需要手动修改)。

模式文件是您数据库的蓝图,它对于为测试或开发设置新环境很有用。它受版本控制,因此您可以查看模式随时间的变化。

db:schema:load 命令从 db/schema.rb(或 db/structure.sql)删除并重新创建数据库模式。它直接执行此操作,一次重放每个迁移。

此命令对于快速将数据库重置为当前模式而无需逐一运行多年的迁移非常有用。例如,运行 db:setup 也会在创建数据库之后和播种之前调用 db:schema:load

您可以将 db:schema:dump 视为写入 schema.rb 文件的命令,将 db:schema:load 视为读取该文件的命令。

8.4. 其他实用命令

8.4.1. bin/rails db:version

bin/rails db:version 命令将显示当前数据库版本,这对于故障排除很有用。

$ bin/rails db:version

database: storage/development.sqlite3
Current version: 20250806173936

8.4.2. db:fixtures:load

db:fixtures:load 命令将 fixture 加载到当前环境的数据库中。要加载特定的 fixture,您可以使用 FIXTURES=x,y。要从 test/fixtures 中的子目录加载,请使用 FIXTURES_DIR=z

$ bin/rails db:fixtures:load
   -> Loading fixtures from test/fixtures/users.yml
   -> Loading fixtures from test/fixtures/books.yml

8.4.3. db:system:change

在现有的 Rails 应用程序中,可以切换到不同的数据库。db:system:change 命令通过将 config/database.yml 文件和您的数据库 gem 更改为目标数据库来帮助实现这一点。

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

8.4.4. db:encryption:init

db:encryption:init 命令生成一组用于在给定环境中配置 Active Record 加密的密钥。

9. 运行测试

bin/rails test 命令可帮助您运行应用程序中不同类型的测试。bin/rails test --help 输出中包含此命令不同选项的良好示例。

您可以通过在文件名后附加行号来运行单个测试

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

您可以通过在文件名后附加行范围来运行行范围内的多个测试

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

您可以同时运行多个文件和目录

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

Rails 附带一个名为 Minitest 的测试框架,您还可以将 Minitest 选项与 test 命令一起使用

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

请参阅测试指南,了解不同类型测试的解释和示例。

10. 其他有用命令

10.1. bin/rails notes

bin/rails notes 命令在您的代码中搜索以特定关键字开头的注释。您可以参考 bin/rails notes --help 以获取使用信息。

默认情况下,它将在 appconfigdblibtest 目录中搜索扩展名为 .builder.rb.rake.yml.yaml.ruby.css.js.erb 的文件中是否存在 FIXME、OPTIMIZE 和 TODO 注释。

$ bin/rails notes
app/controllers/admin/users_controller.rb:
  * [ 20] [TODO] any other way to do this?
  * [132] [FIXME] high priority for next deploy

lib/school.rb:
  * [ 13] [OPTIMIZE] refactor this code to make it faster

10.1.1. 注释

您可以通过使用 -a(或 --annotations)选项来传递特定的注释。请注意,注释是区分大小写的。

$ bin/rails notes --annotations FIXME RELEASE
app/controllers/admin/users_controller.rb:
  * [101] [RELEASE] We need to look at this before next release
  * [132] [FIXME] high priority for next deploy

lib/school.rb:
  * [ 17] [FIXME]

10.1.2. 添加标签

您可以使用 config.annotations.register_tags 添加更多默认标签进行搜索

config.annotations.register_tags("DEPRECATEME", "TESTME")
$ bin/rails notes
app/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. 添加目录

您可以使用 config.annotations.register_directories 添加更多默认搜索目录

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

10.1.4. 添加文件扩展名

您可以使用 config.annotations.register_extensions 添加更多默认文件扩展名

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

10.2. bin/rails tmp:

Rails.root/tmp 目录与 *nix /tmp 目录一样,是用于存放进程 ID 文件和缓存操作等临时文件的位置。

tmp: 命名空间命令将帮助您清除和创建 Rails.root/tmp 目录

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

10.3. bin/rails secret

bin/rails secret 命令生成一个加密安全的随机字符串,用作 Rails 应用程序中的密钥。

$ bin/rails secret
4d39f92a661b5afea8c201b0b5d797cdd3dcf8ae41a875add6ca51489b1fbbf2852a666660d32c0a09f8df863b71073ccbf7f6534162b0a690c45fd278620a63

它对于在应用程序的 config/credentials.yml.enc 文件中设置密钥很有用。

10.4. bin/rails credentials

credentials 命令提供对加密凭据的访问,因此您可以安全地将访问令牌、数据库密码等存储在应用程序内部,而无需依赖大量环境变量。

要将值添加到加密的 YML 文件 config/credentials.yml.enc,您可以使用 credentials:edit 命令

$ bin/rails credentials:edit

这会在编辑器中打开解密的凭据(由 $VISUAL$EDITOR 设置)进行编辑。保存时,内容会自动加密。

您还可以使用 :show 命令查看解密的凭据文件,它可能看起来像这样(这来自示例应用程序,不是敏感数据)

$ bin/rails credentials:show
# aws:
#   access_key_id: 123
#   secret_access_key: 345
active_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

您可以在Rails 安全指南中了解凭据。

请查看 bin/rails credentials --help 的输出中此命令的详细说明。

11. 自定义 Rake 任务

您可能希望在应用程序中创建自定义 rake 任务,例如从数据库中删除旧记录。您可以使用 bin/rails generate task 命令完成此操作。自定义 rake 任务具有 .rake 扩展名,并放置在 Rails 应用程序的 lib/tasks 文件夹中。例如

$ bin/rails generate task cool
create  lib/tasks/cool.rake

cool.rake 文件可以包含以下内容

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

要将参数传递给您的自定义 rake 任务

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

您可以通过将任务放置在命名空间中来对任务进行分组

namespace :db do
  desc "This task has something to do with the database"
  task :my_db_task do
    # ...
  end
end

调用 rake 任务如下所示

$ bin/rails task_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/rails db:my_db_task

如果您需要与应用程序模型交互,执行数据库查询等,您的任务可以依赖于 environment 任务,它将加载您的 Rails 应用程序。

task task_that_requires_app_code: [:environment] do
  puts User.count
end


回到顶部