首页
/ Rails 命令行完全指南:从 `rails new` 到 `bin/rails` 全命令实战

Rails 命令行完全指南:从 `rails new` 到 `bin/rails` 全命令实战

2026-09-07 13:14:09作者:田桥桑Industrious

Ruby on Rails 的命令行工具(CLI)是贯穿整个 Web 应用生命周期的核心生产力入口:从创建工程、生成代码、启动服务器,到操作数据库、运行测试、加密凭据、排查启动故障,几乎所有日常开发动作都可以在终端中完成。本文以官方 Command Line 指南为骨架,结合当前仓库 railties 中命令的真实实现(alias 映射、命令选项、执行器包裹等),系统讲解每个高频命令的用法、参数、别名与底层原理。读完你将能够脱离图形界面,熟练地用命令完成一个 Rails 应用的创建、开发、测试与维护闭环。

总览:bin/rails --help 与命令别名

Rails 命令行的强大之处在于它围绕"约定优于配置"批量生成样板代码。可用命令往往随当前目录(是否处于一个 Rails 应用中)而变化,通过 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.

紧接着会按字母顺序列出其余所有命令及简要描述:

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 ...
db:migrate                         Migrate the database ...
db:migrate:status                  Display status of migrations
db:rollback                        Roll the schema back to ...
version                            Show the Rails version
yarn:install                       Install all JavaScript dependencies as ...
zeitwerk:check                     Check project structure for Zeitwerk ...

快捷别名从哪来

指南中反复提到的 gscd 等别名并非魔法,而是定义在 commands.rb 中:该文件用一张 Hash 把用户输入映射到正式命令名("g" => "generate""db" => "dbconsole""r" => "runner""t" => "test"),再交给 Rails::Command.invoke 分发执行。因此 bin/rails gbin/rails dbin/rails rbin/rails db 在底层走的是完全相同的命令处理器,仅仅是入口不同。

--help 是自文档的入口

任何子命令都可以追加 -h--help 获得详细用法,例如查看路由命令的可用过滤选项:

$ 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

生成器类的帮助信息更为详尽,例如 bin/rails generate model --help 会打印两页描述。这段帮助文本直接来自 railties 中对应 generator 的文档注释,意味着"描述即帮助、帮助即描述"。

创建新应用:rails new

rails new 需要本机先安装 rails gem(gem install rails,分步指引参见 安装指南)。它的第一个参数是应用名,执行后会一次性铺设完整的默认目录结构与可运行的示例代码:

$ 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 命令支持大量选项来调整默认行为,也可以配合应用模板批量定制生成内容。

配置不同的数据库:--database

默认数据库是 SQLite,若想使用 PostgreSQL 则传入 --database

$ rails new booknotes --database=postgresql

二者的主要差别体现在生成的 config/database.yml 中。PostgreSQL 版本大致如下(片段):

# PostgreSQL. Versions 10.0 and up are supported.
#
# Install the pg driver:
#   gem install pg
# On macOS with Homebrew:
#   gem install pg -- --with-pg-config=/opt/homebrew/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
  max_connections: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

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

选择 --database=postgresql 还会连带修改其他生成内容,比如把 pg gem 写进 Gemfile

跳过默认模块:--skip-*

rails new 默认生成数十个文件。若不需要某模块,可用各类 --skip 选项。注意模块间存在依赖关系,例如跳过 Active Storage 会连带跳过依赖它的模块:

$ 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]

rails new --help 的 Options 一节列出了全部可跳过项。仓库中 railties 负责各框架模块的组织与注册(见 engine.rbrailtie.rb),这些 skip 开关正是在应用装配(application boot)阶段生效。

启动服务器:bin/rails server

bin/rails server 启动随 Rails 内置的 Puma Web 服务器,用于在浏览器中访问应用:

$ cd my_app
$ bin/rails server
=> Booting Puma
=> Rails 8.2.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

默认监听 3000 端口,浏览器访问 http://localhost:3000 即可看到运行中的应用。常用别名是 bin/rails s。端口、环境、绑定地址与守护模式等选项在 railties 的 server_command.rb 中通过 class_option 定义,和指南完全对应:

$ bin/rails server -e production -p 4000   # 改环境、改端口
  • -p / --port:指定端口,默认 3000;
  • -e / --environment:指定运行环境,默认 development;
  • -b / --binding:绑定到指定 IP,开发环境默认 localhost,其他环境默认 0.0.0.0
  • -d / --daemon:以守护进程方式运行;
  • -u / --using:指定 Rack 服务器(thin/puma/webrick);
  • -P / --pid:指定 PID 文件;
  • -C / --dev_caching:开发模式下是否开启缓存。

生成代码:bin/rails generate

bin/rails generate(短别名 bin/rails g)用于生成模型、控制器、迁移、完整 scaffold 等各类文件。不带参数执行会列出全部可用生成器:

$ 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 会额外注册生成器;开发者也可以编写自己的生成器。railties 统一在此处汇总内置生成器,而 --pretend(-p)选项可以"演练"一次生成过程而不真正改动文件,适合在正式生成前确认影响范围。

生成控制器

$ 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。实际生成一个 Greetings 控制器及其 hello action:

$ 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

可以看到它同时创建了控制器文件、视图目录与视图、功能测试文件、视图 helper,并追加了一条路由。接着可以改控制器和视图,让页面真正输出内容:

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

然后启动服务器访问 http://localhost:3000/greetings/hello 即可看到消息。

生成模型

模型生成器的 Usage 非常直观:

$ 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
  • type 参数的可用字段类型以 ActiveRecord 的 add_column 为准(可在仓库 schema_statements 中找到对应实现);
  • field:type:index 三段的第三段 index 表示为该列生成数据库索引;
  • 不指定 type 时默认类型是 string
  • created_at / updated_at 时间戳默认自动加上,无需手写;
  • 特殊组合 password:digest 会生成 string 类型的 password_digest 字段,并在模型与测试中配置好 Active Model 的 has_secure_password

生成的迁移需要随后执行 bin/rails db:migrate 才会真正落到数据库。

生成资源:resourcescaffold

Rails 还提供一次生成整套 CRUD 资源的生成器:resourcescaffold 更轻量。

resource 生成模型、迁移、空控制器、路由和测试,但不生成视图、也不往控制器里填充 CRUD 方法,适合 API 场景或想手动编写 action 的情况:

$ 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

scaffold 则生成完整全套:模型、控制器、视图(HTML 与 JSON)、路由、迁移、测试和 helper 文件,适合快速原型化 CRUD 界面或作为定制起点:

$ 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 建出 posts 表(参见下文数据库管理),再启动服务器访问 http://localhost:3000/posts,即可完成帖子的增删改查。scaffold 生成的测试文件只是骨架,仍需你补写真正的断言,参见测试指南

撤销生成:bin/rails destroy

如果手误生成了错误的模型(比如把 article 拼成 artcle),手工逐个删除文件很繁琐。destroy(别名 bin/rails d)是 generate 的逆操作,能自动还原生成器所做的一切:

$ 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

撤销它:

$ 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

与应用交互:console、dbconsole、query、runner、boot

bin/rails console:交互式探索整个应用

bin/rails console 把完整的 Rails 环境(模型、数据库等)加载进一个 IRB 风格的交互 shell,非常适合在命令行中试验代码、原型化想法,或在不打开浏览器的情况下创建/更新数据库记录。console 的选项同样定义在 console_command.rb,例如 --sandbox(-s)选项。

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

sandbox 模式bin/rails console --sandbox 会把所有数据库操作包在一个事务里,退出时整体回滚,是安全测试破坏性改动的利器:

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

指定环境:用 -e 参数切换:

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

app 对象:免启动服务器发请求

Console 内可访问 apphelper 两个对象。app 能调用命名路由 helper:

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

更能直接"发请求",无需真正启动服务器:

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

注意上面的请求必须带 "Host" 头,因为底层 Rack 客户端在未指定 Host 时默认使用 "www.example.com";可通过配置或初始化器让应用始终使用 localhost。之所以能这样"发请求",是因为 app 对象与集成测试使用的是同一个类:

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

app 还暴露 app.cookiesapp.sessionapp.postapp.response 等方法,可直接在 Console 中模拟并调试集成测试。ActionDispatch::Integration::Session 的实现位于 action_dispatch/testing/integration.rb(见 actionpack 的 testing 目录)。

helper 对象:直达视图层

helper 是通往 Rails 视图层的直接入口,可测试各类视图格式化/工具方法以及应用自定义 helper(位于 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"

bin/rails dbconsole:直接进入数据库 CLI

dbconsole(别名 bin/rails db)会根据 config/database.yml 与当前 Rails 环境,自动推断你使用的数据库并启动对应的命令行客户端。以 PostgreSQL 为例:

$ 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
 ...

它本质上等价于用 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。其入口实现在 dbconsole_command.rb:它会先从应用的多数据库配置中解析出目标 db_config,再交给对应的连接适配器类启动客户端(还支持 --include-password 等透传选项)。多数据库环境下默认连接主库,可用 --database / --db 指定:

$ bin/rails dbconsole --database=animals

bin/rails query:只读查询与模式探索

query 命令运行只读数据库查询并返回结构化 JSON 输出。它默认连接只读副本角色并禁止数据库写入;--sql 标志限定只能执行原生 SQL。ActiveRecord 表达式按 Ruby 求值,信任模型与 bin/rails runnerbin/rails console 一致:

$ bin/rails query "Account.where(plan: 'premium').limit(10)"

原生 SQL 需加 --sql

$ bin/rails query --sql "SELECT * FROM accounts LIMIT 10"

结果分页输出,用 --page--per 翻页(每页上限 10000,见 query_command.rb):

$ bin/rails query "Account.all" --page 2 --per 50

管道接 jq 可获得可读排版:

$ bin/rails query "Account.first" | jq

query 还有三个子命令:

$ bin/rails query schema          # 列出所有表,或指定表详情(列、索引、枚举、关联)
$ bin/rails query schema accounts
$ bin/rails query models          # 列出全部 ActiveRecord 模型及其表名与关联
$ bin/rails query explain "Account.where(plan: 'premium')"   # 显示表达式查询计划

多数据库时用 --database / --db 指定配置:

$ bin/rails query "Account.count" --database primary_replica

从源码看,只读保障是通过 query_command.rb 中的只读连接封装实现的(with_readonly_connectionreading_role_available? 等逻辑会优先选择 reading role)。

bin/rails runner:免交互执行 Ruby 脚本

runner(别名 bin/rails r)在不打开 Console 的前提下于应用上下文中执行 Ruby 代码,适合一次性任务:

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

$ bin/rails runner 'MyJob.perform_now'

指定环境:

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

也可以直接执行一个 Ruby 文件:

$ bin/rails runner lib/path_to_ruby_script.rb

默认情况下,runner 脚本会自动被 Rails Executor(ActiveSupport::Executor 的实例)包裹,为在 Rails 应用内运行任意 Ruby 建立一个"安全区",使 autoloader、中间件栈和 Active Support 钩子的行为保持一致。因此上面的文件执行在功能上等价于:

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

如需关闭该行为,可用 --skip-executor-w)。这与 runner_command.rb 中的实现一致:代码优先按文件处理(File.exist?Kernel.load),否则 eval 执行;conditional_executor 根据 options[:skip_executor] 决定是否包裹。此外还支持用 - 从标准输入读取代码(stdin 模式)。

bin/rails boot:只启动、只诊断

bin/rails boot 是一个底层命令,唯一职责是启动 Rails 应用——具体来说加载 config/boot.rbconfig/application.rb,让应用环境就绪后立即退出,不做任何其他事。当应用启动失败、想隔离启动阶段(不跑迁移、不起服务器)时,它可以作为一个极简测试;也常被包在 profiler 里测量应用初始化耗时。

检视应用:routes、about、initializers、middleware、stats

bin/rails routes:查看路由表

routes 列出应用中全部已定义路由,包括 URI Pattern、HTTP verb 与映射的 Controller#Action:

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

用选项收窄输出:

# 只显示控制器名含 "users" 的路由
$ bin/rails routes --controller users

# 显示 Admin::UsersController 处理的路由
$ bin/rails routes -c admin/users

# 用 -g / --grep 按名称、路径或 controller/action 搜索
$ bin/rails routes -g users

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

开发模式下也可以直接访问 http://localhost:3000/rails/info/routes 查看同一份路由信息。

bin/rails about:环境与版本快照

about 显示 Ruby、RubyGems、Rails 版本、数据库适配器、schema 版本等环境信息,在求助排查、确认安全补丁是否影响你时很有用:

$ bin/rails about
About your application's environment
Rails version             8.2.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

bin/rails initializers:按执行顺序打印初始化器

当初始化器彼此依赖、执行顺序至关重要时,该命令按 Rails 实际调用顺序打印全部初始化器。框架初始化器先运行,然后才是定义在 config/initializers 中的应用初始化器:

$ 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

bin/rails middleware:检视 Rack 中间件栈

middleware 按每个请求实际经过的顺序显示完整的 Rack 中间件栈:

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

这能帮你分辨哪些中间件来自 Rails 内置、哪些来自 gem(例如 Devise 注入的 Warden::Manager),也是调试与性能分析的好帮手。

bin/rails stats:代码统计

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 |
...
+----------------------+--------+--------+---------+---------+-----+-------+
| Total                |   1924 |   1541 |      26 |      58 |   2 |    24 |
+----------------------+--------+--------+---------+---------+-----+-------+
  Code LOC: 1411     Test LOC: 130     Code to Test Ratio: 1:0.1

bin/rails time:zones:all / time:zones:local

打印 Active Support 已知的全部时区及对应的 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、校验用户输入或排错时,它都能帮你拿到精确的时区名称拼写(例如 "Pacific Time (US & Canada)")。

管理静态资源:bin/rails assets:*

先用 bin/rails -T 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
  • assets:precompile:预编译 app/assets 下的资源(详见 Asset Pipeline 指南);
  • assets:clean:清理旧的已编译资源,配合滚动发布(rolling deploy)在构建新资源期间仍可链接旧文件;
  • assets:clobber:彻底清空 public/assets

管理数据库: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`

数据库的建、删、种子与重置

  • db:create / db:drop:为当前环境创建/删除数据库(db:create:alldb:drop:all 作用于全部环境);
  • db:seed:从 db/seeds.rb 加载示例数据;db:seed:replant 先清空当前环境各表再灌种子;
  • db:setup:创建所有数据库、加载 schema、灌种子(不先 drop);
  • db:reset:先 drop 再按 schema 重建当前环境所有数据库并灌种子,可视为上面命令的组合。

关于种子数据可参见 Active Record Migrations 指南 中"migrations and seed data"一节。

迁移:migrate / up / down / rollback / redo / status

db:migrate 是最高频的命令之一:执行所有尚未运行的新迁移。db:migrate:updb:migrate:down 分别针对指定 VERSION 运行迁移的 up / 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

迁移概念的完整说明见迁移指南

Schema 管理:dump 与 load

  • db:schema:dump:读取当前数据库结构并写入 db/schema.rb(若配置 schema 格式为 sql 则写 db/structure.sql)。跑完迁移后 Rails 会自动调用 schema:dump,使 schema 文件始终最新,无需手动修改。schema 文件是数据库蓝本、纳入版本管理,可用于搭建测试/开发新环境并追溯 schema 变更历史。
  • db:schema:load:根据 db/schema.rb(或 structure.sql)直接 drop 并重建 schema,而逐条回放迁移。它适合快速把库重置到当前 schema,而不用一条条跑数年累积的迁移。例如 db:setup 在建库后、灌种子前也会调用它。

可以这样记忆:db:schema:dump 负责写入 schema 文件,db:schema:load 负责读取该文件。

其他工具命令

db:version:显示当前数据库版本号(schema 版本),便于排查:

$ bin/rails db:version

database: storage/development.sqlite3
Current version: 20250806173936

db:fixtures:load:把 fixtures 载入当前环境数据库;用 FIXTURES=x,y 指定特定 fixtures,用 FIXTURES_DIR=z 指定 test/fixtures 下的子目录:

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

db:system:change:在既有应用中切换数据库系统。它会改写 config/database.yml 并把 Gemfile 中的数据库 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
...

db:encryption:init:为指定环境生成一组用于配置 Active Record 加密的密钥(对应 config/credentials.yml.enc 中的 active_record_encryption 段)。

运行测试: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 选项:

# 只运行名称匹配正则 /validation/ 的测试
$ bin/rails test -n /validation/

不同类型测试的写法与示例参见测试指南

其他实用命令

bin/rails notes:代码注释巡查

notes 搜索代码中以特定关键词开头的注释。默认在 appconfigdblibtest 目录中查找 FIXME、OPTIMIZE、TODO 三类注解,文件扩展名涵盖 .builder.rb.rake.yml.yaml.ruby.css.js.erb

$ 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

-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]

添加自定义注解标签(默认只有 FIXME/OPTIMIZE/TODO):

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

添加搜索目录

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

添加文件扩展名(需配套正则以识别注解写法):

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

这些配置入口对应仓库中的 source_annotation_extractor.rb,该类维护了默认标签、目录与扩展名,并支持通过 register_* 在应用配置中扩展。

bin/rails tmp::临时文件管理

Rails.root/tmp 相当于 *nix 的 /tmp,存放 pid 文件、缓存动作等临时内容:

$ 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.

bin/rails secret:生成密钥串

secret 生成一段密码学安全的随机字符串,用于应用密钥:

$ bin/rails secret
4d39f92a661b5afea8c201b0b5d797cdd3dcf8ae41a875add6ca51489b1fbbf2852a666660d32c0a09f8df863b71073ccbf7f6534162b0a690c45fd278620a63

它可用于设置应用 config/credentials.yml.enc 中的密钥。

bin/rails credentials:加解密凭据

credentials:* 命令管理加密凭据,让你可以把访问令牌、数据库密码等安全地放在应用内,而不依赖大量环境变量。

编辑bin/rails credentials:edit$VISUAL$EDITOR 指定的编辑器打开解密后的凭据文件,保存时自动加密回 config/credentials.yml.enc

查看bin/rails credentials: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 Security 指南中"Custom Credentials"一节,bin/rails credentials --help 也提供详细说明。相关命令实现位于 credentialsencrypted

自定义 Rake 任务

想在应用中添加自定义任务(例如清理数据库中的旧记录),用 bin/rails generate task

$ 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

传递参数

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

调用任务

$ 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

这些任务经由 railties 的 Rake 集成装载,最终统一由 bin/rails 入口调度执行。

速查:高频命令与别名

命令 别名 作用
rails new app_name 创建新应用(可配 --database--skip-*
bin/rails server s 启动 Puma 开发服务器(-p 端口、-e 环境、-b 绑定、-d 守护)
bin/rails generate g 生成 model/controller/resource/scaffold 等代码
bin/rails destroy d 撤销 generate 产生的文件
bin/rails console c 加载完整应用的 IRB shell(--sandbox 回滚)
bin/rails dbconsole db database.yml 进入对应数据库 CLI
bin/rails runner r 在应用上下文执行 Ruby 代码/脚本(--skip-executor 关闭包裹)
bin/rails test t 运行测试(可按行号/区间/正则过滤)
bin/rails routes 列出/过滤路由(-c-g--expanded
bin/rails db:migrate 执行待运行迁移(配 db:migrate:status/up/down/redo/rollback
bin/rails db:create / db:setup / db:reset 建库 / 初始化 / 重置数据库
bin/rails notes 搜索 TODO/FIXME/OPTIMIZE 等注释(可扩展标签与目录)
bin/rails credentials:edit 编辑加密凭据文件
bin/rails about 输出应用环境与版本信息

别名映射的完整清单定义在 railties/lib/rails/commands.rb,本仓库中各命令的实际 CLI 参数(如 server 的 -p/-e/-b/-d/-u/-P/-C、console 的 --sandbox、runner/console 的 --skip-executor)都可以在对应的 commands/ 子目录源码中逐一核对,是理解"命令来自何方"的第一手资料。

登录后查看全文
热门项目推荐
相关项目推荐

项目优选

收起
kernelkernel
deepin linux kernel
C
33
18
ops-transformerops-transformer
本项目是CANN提供的transformer类大模型算子库,实现网络在NPU上加速计算。
C++
1.13 K
2.75 K
pytorchpytorch
作为 Ascend for PyTorch 社区的核心组件,TorchNPU 是昇腾专为 PyTorch 打造的深度学习适配插件,使 PyTorch 框架能够直接调用昇腾 NPU,为开发者提供昇腾 AI 处理器的超强算力。
Python
857
1.35 K
docsdocs
暂无描述
Markdown
897
5.8 K
kernelkernel
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
529
593
ops-nnops-nn
本项目是CANN提供的神经网络类计算算子库,实现网络在NPU上加速计算。
C++
916
1.83 K
jiuwenswarmjiuwenswarm
JiuwenSwarm 是一款基于openJiuwen开发的智能AI Agent,它能够将大语言模型的强大能力,通过你日常使用的各类通讯应用,直接延伸至你的指尖。
Python
3.58 K
1.01 K
ops-mathops-math
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
1.35 K
1.46 K
cann-learning-hubcann-learning-hub
CANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。
Jupyter Notebook
1.01 K
515
AscendNPU-IRAscendNPU-IR
AscendNPU-IR是基于MLIR(Multi-Level Intermediate Representation)构建的,面向昇腾亲和算子编译时使用的中间表示,提供昇腾完备表达能力,通过编译优化提升昇腾AI处理器计算效率,支持通过生态框架使能昇腾AI处理器与深度调优
C++
547
388