v7.0.8
Veja mais em rubyonrails.org: Mais Ruby on Rails

Linhas de Comando do Rails

Depois de ler este guia, você saberá:

Esse tutorial considera que você já tenha um conhecimento básico de Rails, ou tenha lido o Começando com o Rails.

1 Criando um app Rails

Primeiro, vamos criar uma aplicação Rails simples usando o comando rails new.

Usaremos esta aplicação para brincar e descobrir todos os comandos descritos neste guia.

Você pode instalar a gem rails digitando gem install rails, caso ainda não a tenha.

1.1 rails new

O primeiro argumento que passaremos ao comando rails new é o nome da aplicação.

$ 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

Rails construirá o que parece ser muita coisa para um comando tão pequeno! Temos toda a estrutura de diretórios do Rails com todo o código que precisamos para rodar nossa aplicação.

Caso deseje que algum arquivo ou biblioteca não seja gerado, podemos adicionar qualquer um dos seguintes argumentos ao comando rails new:

Argument Description
--skip-git Pula git init, .gitignore, and .gitattributes
--skip-keeps Pula source control .keep files
--skip-action-mailer Pula Action Mailer files
--skip-action-mailbox Pula Action Mailbox gem
--skip-action-text Pula Action Text gem
--skip-active-record Pula Active Record files
--skip-active-job Pula Active Job
--skip-active-storage Pula Active Storage files
--skip-action-cable Pula Action Cable files
--skip-asset-pipeline Pula Asset Pipeline
--skip-javascript Pula JavaScript files
--skip-hotwire Pula Hotwire integration
--skip-jbuilder Pula jbuilder gem
--skip-test Pula test files
--skip-system-test Pula system test files
--skip-bootsnap Pula bootsnap gem

Estas são algumas das opções aceitas pelo rails new. Para a lista completa de opções, digite rails new --help.

2 Noções Básicas de Linha de Comando

Existem alguns comandos essenciais para o uso cotidiano do Rails. Na ordem de quanto você provavelmente irá utilizá-los são:

  • 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

Você pode obter uma lista dos comandos do Rails disponíveis, que geralmente depende de seu diretório atual, escrevendo rails --help. Cada comando possui uma descrição, que deverá ajudá-lo a encontrar o que precisa.

$ rails --help
Usage: rails COMMAND [ARGS]

Os comandos de Rails mais comuns são:
 generate    Gera um novo código (tecla de atalho: "g")
 console     Inicia um console Rails (tecla de atalho: "c")
 server      Inicia um servidor Rails (tecla de atalho: "s")
 ...

Todos os comandos podem ser executados com -h (ou --help) para mais informações.

Além desses comandos, existem:
 about                               Lista a versão de todos os Rails ...
 assets:clean[keep]                  Remove os *assets* compilados antigos
 assets:clobber                      Remove os *assets* compilados
 assets:environment                  Carrega o ambiente de compilação de *assets*
 assets:precompile                   Compila todos os *assets* ...
 ...
 db:fixtures:load                    Carrega *fixtures* no ...
 db:migrate                          Migra o banco de dados ...
 db:migrate:status                   Mostra o status da migração
 db:rollback                         Retorna o *schema* de volta para ...
 db:schema:cache:clear               Limpa um arquivo db/schema_cache.yml
 db:schema:cache:dump                Cria um arquivo db/schema_cache.yml
 db:schema:dump                      Cria o schema do banco de dados (db/schema.rb ou db/structure.sql ...
 db:schema:load                      Carrega um arquivo de schema de banco de dados (db/schema.rb ou db/structure.sql ...
 db:seed                             Carrega os dados da seed ...
 db:version                          Recupera o *schema* atual ...
 ...
 restart                             Reinicia o aplicativo tocando em ...
 tmp:create                          Cria diretórios tmp ...

2.1 bin/rails server

O comando bin/rails server inicia um servidor web chamado Puma que vem incluído com o Rails. Você usará esse comando toda vez que quiser acessar sua aplicação através de um navegador web.

Sem mais trabalho, bin/rails server rodará nosso app Rails novo em folha:

$ cd my_app
$ bin/rails server
=> Booting Puma
=> Rails 7.0.0 application starting in development
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Version 3.12.1 (ruby 2.5.7-p206), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop

Com apenas três comandos nós subimos um servidor Rails escutando na porta 3000. Vá para o navegador e acesse http://localhost:3000, você verá um app Rails básico rodando.

Você também pode usar o alias "s" para iniciar o servidor: bin/rails s.

O servidor pode ser direcionado para diferentes portas usando a opção -p. O ambiente padrão development também pode ser alterado usando -e.

$ bin/rails server -e production -p 4000

A opção -b aponta o servidor para o IP especificado, por padrão é localhost. É possível rodar um servidor como daemon (plano de fundo) passando a opção -d.

2.2 bin/rails generate

The bin/rails generate command uses templates to create a whole lot of things. Running bin/rails generate by itself gives a list of available generators:

You can also use the alias "g" to invoke the generator command: bin/rails g.

$ bin/rails generate
Usage: rails generate GENERATOR [args] [options]

...
...

Please choose a generator below.

Rails:
  assets
  channel
  controller
  generator
  ...
  ...

You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!

Using generators will save you a large amount of time by writing boilerplate code, code that is necessary for the app to work.

Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:

All Rails console utilities have help text. As with most *nix utilities, you can try adding --help or -h to the end, for example bin/rails server --help.

$ bin/rails generate controller
Usage: bin/rails generate controller NAME [action action] [options]

...
...

Description:
    ...

    To create a controller within a module, specify the controller name as a path like 'parent_module/controller_name'.

    ...

Example:
    `bin/rails generate controller CreditCards open debit credit close`

    Credit card controller with URLs 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

The controller generator is expecting parameters in the form of generate controller ControllerName action1 action2. Let's make a Greetings controller with an action of hello, which will say something nice to us.

$ 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

What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a view file, a functional test file, a helper for the view, a JavaScript file, and a stylesheet file.

Check out the controller and modify it a little (in app/controllers/greetings_controller.rb):

class GreetingsController < ApplicationController
  def hello
    @message = "Hello, how are you today?"
  end
end

Then the view, to display our message (in app/views/greetings/hello.html.erb):

<h1>A Greeting for You!</h1>
<p><%= @message %></p>

Fire up your server using bin/rails server.

$ bin/rails server
=> Booting Puma...

The URL will be http://localhost:3000/greetings/hello.

With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the index action of that controller.

Rails comes with a generator for data models too.

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

...

ActiveRecord options:
      [--migration], [--no-migration]        # Indicates when to generate migration
                                             # Default: true

...

Description:
    Generates a new model. Pass the model name, either CamelCased or
    under_scored, and an optional list of attribute pairs as arguments.

...

For a list of available field types for the type parameter, refer to the API documentation for the add_column method for the SchemaStatements module. The index parameter generates a corresponding index for the column.

But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A scaffold in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.

We will set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.

$ bin/rails generate scaffold HighScore game:string score:integer
    invoke  active_record
    create    db/migrate/20190416145729_create_high_scores.rb
    create    app/models/high_score.rb
    invoke    test_unit
    create      test/models/high_score_test.rb
    create      test/fixtures/high_scores.yml
    invoke  resource_route
     route    resources :high_scores
    invoke  scaffold_controller
    create    app/controllers/high_scores_controller.rb
    invoke    erb
    create      app/views/high_scores
    create      app/views/high_scores/index.html.erb
    create      app/views/high_scores/edit.html.erb
    create      app/views/high_scores/show.html.erb
    create      app/views/high_scores/new.html.erb
    create      app/views/high_scores/_form.html.erb
    invoke    test_unit
    create      test/controllers/high_scores_controller_test.rb
    create      test/system/high_scores_test.rb
    invoke    helper
    create      app/helpers/high_scores_helper.rb
    invoke      test_unit
    invoke    jbuilder
    create      app/views/high_scores/index.json.jbuilder
    create      app/views/high_scores/show.json.jbuilder
    create      app/views/high_scores/_high_score.json.jbuilder

The generator creates the model, views, controller, resource route, and database migration (which creates the high_scores table) for HighScore. And it adds tests for those.

The migration requires that we migrate, that is, run some Ruby code (the 20190416145729_create_high_scores.rb file from the above output) to modify the schema of our database. Which database? The SQLite3 database that Rails will create for you when we run the bin/rails db:migrate command. We'll talk more about that command below.

$ bin/rails db:migrate
==  CreateHighScores: migrating ===============================================
-- create_table(:high_scores)
   -> 0.0017s
==  CreateHighScores: migrated (0.0019s) ======================================

Let's talk about unit tests. Unit tests are code that tests and makes assertions about code. In unit testing, we take a little part of code, say a method of a model, and test its inputs and outputs. Unit tests are your friend. The sooner you make peace with the fact that your quality of life will drastically increase when you unit test your code, the better. Seriously. Please visit the testing guide for an in-depth look at unit testing.

Let's see the interface Rails created for us.

$ bin/rails server

Go to your browser and open http://localhost:3000/high_scores, now we can create new high scores (55,160 on Space Invaders!)

2.3 bin/rails console

O comando console permite a interação com a aplicação Rails através da linha de comando. Por trás, bin/rails console usa o IRB, então se você já o utilizou, estará em casa. Esse comando é útil para testar rapidamente idéias de código e alterar dados server-side sem acessar a aplicação via web.

Você também pode usar o alias "c" para iniciar o console: bin/rails c.

Você pode especificar o ambiente em que o comando console deverá operar:

$ bin/rails console -e staging

Se desejar testar o código sem alterar nenhum dado, pode fazer isso chamando bin/rails console --sandbox.

$ bin/rails console --sandbox
Loading development environment in sandbox (Rails 7.0.0)
Any modifications you make will be rolled back on exit
irb(main):001:0>
2.3.1 Os objetos app e helper

Dentro do bin/rails console você tem acesso as instâncias app e helper.

Com o método app você pode acessar as rotas definidas, assim como realizar requisições.

irb> app.root_path
=> "/"

irb> app.get _
Started GET "/" for 127.0.0.1 at 2014-06-19 10:41:57 -0300
...

Com o método helper é possível acessar os métodos helpers definidos na sua aplicação.

irb> helper.time_ago_in_words 30.days.ago
=> "about 1 month"

irb> helper.my_custom_helper
=> "my custom helper"

2.4 bin/rails dbconsole

bin/rails dbconsole figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It 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 the primary database by default. You can specify which database to connect to using --database or --db:

$ bin/rails dbconsole --database=animals

2.5 bin/rails runner

runner runs Ruby code in the context of Rails non-interactively. For instance:

$ bin/rails runner "Model.long_running_method"

You can also use the alias "r" to invoke the runner: bin/rails r.

You can specify the environment in which the runner command should operate using the -e switch.

$ bin/rails runner -e staging "Model.long_running_method"

You can even execute ruby code written in a file with runner.

$ bin/rails runner lib/code_to_be_run.rb

2.6 bin/rails destroy

Think of destroy as the opposite of generate. It'll figure out what generate did, and undo it.

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

$ bin/rails generate model Oops
      invoke  active_record
      create    db/migrate/20120528062523_create_oops.rb
      create    app/models/oops.rb
      invoke    test_unit
      create      test/models/oops_test.rb
      create      test/fixtures/oops.yml
$ bin/rails destroy model Oops
      invoke  active_record
      remove    db/migrate/20120528062523_create_oops.rb
      remove    app/models/oops.rb
      invoke    test_unit
      remove      test/models/oops_test.rb
      remove      test/fixtures/oops.yml

2.7 bin/rails about

bin/rails about gives information about version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version. It is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.

$ bin/rails about
About your application's environment
Rails version             7.0.0
Ruby version              2.7.0 (x86_64-linux)
RubyGems version          2.7.3
Rack version              2.0.4
JavaScript Runtime        Node.js (V8)
Middleware:               Rack::Sendfile, ActionDispatch::Static, ActionDispatch::Executor, ActiveSupport::Cache::Strategy::LocalCache::Middleware, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, ActionDispatch::RemoteIp, Sprockets::Rails::QuietAssets, Rails::Rack::Logger, ActionDispatch::ShowExceptions, WebConsole::Middleware, ActionDispatch::DebugExceptions, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, Rack::Head, Rack::ConditionalGet, Rack::ETag
Application root          /home/foobar/my_app
Environment               development
Database adapter          sqlite3
Database schema version   20180205173523

2.8 bin/rails assets:

You can precompile the assets in app/assets using bin/rails assets:precompile, and remove older compiled assets using bin/rails assets:clean. The assets:clean command allows for rolling deploys that may still be linking to an old asset while the new assets are being built.

If you want to clear public/assets completely, you can use bin/rails assets:clobber.

2.9 bin/rails db:

The most common commands of the db: rails namespace are migrate and create, and it will pay off to try out all of the migration rails commands (up, down, redo, reset). bin/rails db:version is useful when troubleshooting, telling you the current version of the database.

More information about migrations can be found in the Migrations guide.

2.10 bin/rails notes

bin/rails notes searches through your code for comments beginning with a specific keyword. You can refer to bin/rails notes --help for information about usage.

By default, it will search in app, config, db, lib, and test directories for FIXME, OPTIMIZE, and TODO annotations in files with extension .builder, .rb, .rake, .yml, .yaml, .ruby, .css, .js, and .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
  * [ 17] [FIXME]
2.10.1 Annotations

You can pass specific annotations by using the --annotations argument. By default, it will search for FIXME, OPTIMIZE, and TODO. Note that annotations are case sensitive.

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

You can add more default tags to search for by using config.annotations.register_tags. It receives a list of 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
2.10.3 Directories

You can add more default directories to search from by using config.annotations.register_directories. It receives a list of directory names.

config.annotations.register_directories("spec", "vendor")
$ 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
  * [ 17] [FIXME]

spec/models/user_spec.rb:
  * [122] [TODO] Verify the user that has a subscription works

vendor/tools.rb:
  * [ 56] [TODO] Get rid of this dependency
2.10.4 Extensions

You can add more default file extensions to search from by using config.annotations.register_extensions. It receives a list of extensions with its corresponding regex to match it up.

config.annotations.register_extensions("scss", "sass") { |annotation| /\/\/\s*(#{annotation}):?\s*(.*)$/ }
$ bin/rails notes
app/controllers/admin/users_controller.rb:
  * [ 20] [TODO] any other way to do this?
  * [132] [FIXME] high priority for next deploy

app/assets/stylesheets/application.css.sass:
  * [ 34] [TODO] Use pseudo element for this class

app/assets/stylesheets/application.css.scss:
  * [  1] [TODO] Split into multiple components

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

spec/models/user_spec.rb:
  * [122] [TODO] Verify the user that has a subscription works

vendor/tools.rb:
  * [ 56] [TODO] Get rid of this dependency

2.11 bin/rails routes

bin/rails routes will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.

2.12 bin/rails test

A good description of unit testing in Rails is given in A Guide to Testing Rails Applications

Rails comes with a test framework called minitest. Rails owes its stability to the use of tests. The commands available in the test: namespace helps in running the different tests you will hopefully write.

2.13 bin/rails tmp:

The Rails.root/tmp directory is, like the *nix /tmp directory, the holding place for temporary files like process id files and cached actions.

The tmp: namespaced commands will help you clear and create the Rails.root/tmp directory:

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

2.14 Miscellaneous

  • bin/rails initializers prints out all defined initializers in the order they are invoked by Rails.
  • bin/rails middleware lists Rack middleware stack enabled for your app.
  • bin/rails stats is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
  • bin/rails secret will give you a pseudo-random key to use for your session secret.
  • bin/rails time:zones:all lists all the timezones Rails knows about.

2.15 Rake Tasks customizadas

Rake tasks customizadas tem a extensão .rake e são localizadas em Rails.root/lib/tasks. Você pode criá-las com o comando bin/rails generate task.

desc "Sou uma descrição curta, mas compreensiva para a minha *task* legal"
task task_name: [:prerequisite_task, :another_task_we_depend_on] do
  # Toda a mágica vai aqui
  # Qualquer código Ruby válido é permitido
end

Para passar argumentos para a sua rake task customizada:

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

Você pode agrupar tasks colocando-as em namespaces:

namespace :db do
  desc "Esta *task* não faz nada"
  task :nothing do
    # Sério, nada
  end
end

A chamada das tasks ficará assim:

$ bin/rails task_name
$ bin/rails "task_name[value 1]" # toda a string deve estar entre aspas
$ bin/rails "task_name[value 1,value2,value3]" # separe múltiplos argumentos com vírgula
$ bin/rails db:nothing

Se você precisar interagir com os models da sua aplicação, realizar consultas no banco de dados, etc., sua task deve depender da task environment, que carregará todo o código da aplicação.

3 The Rails Advanced Command Line

More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.

3.1 Rails with Databases and SCM

When creating a new Rails application, you have the option to specify what kind of database and what kind of source code management system your application is going to use. This will save you a few minutes, and certainly many keystrokes.

Let's see what a --git option and a --database=postgresql option will do for us:

$ mkdir gitapp
$ cd gitapp
$ git init
Initialized empty Git repository in .git/
$ rails new . --git --database=postgresql
      exists
      create  app/controllers
      create  app/helpers
...
...
      create  tmp/cache
      create  tmp/pids
      create  Rakefile
add 'Rakefile'
      create  README.md
add 'README.md'
      create  app/controllers/application_controller.rb
add 'app/controllers/application_controller.rb'
      create  app/helpers/application_helper.rb
...
      create  log/test.log
add 'log/test.log'

We had to create the gitapp directory and initialize an empty git repository before Rails would add files it created to our repository. Let's see what it put in our database configuration:

$ cat config/database.yml
# 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 macOS with MacPorts:
#   gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/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.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: gitapp_development
...
...

It also generated some lines in our database.yml configuration corresponding to our choice of PostgreSQL for database.

The only catch with using the SCM options is that you have to make your application's directory first, then initialize your SCM, then you can run the rails new command to generate the basis of your app.

Feedback

Você é incentivado a ajudar a melhorar a qualidade deste guia.

Por favor, contribua caso veja quaisquer erros, inclusive erros de digitação. Para começar, você pode ler nossa sessão de contribuindo com a documentação.

Você também pode encontrar conteúdo incompleto ou coisas que não estão atualizadas. Por favor, adicione qualquer documentação em falta na main do Rails. Certifique-se de checar o Edge Guides (en-US) primeiro para verificar se o problema já foi resolvido ou não no branch main. Verifique as Diretrizes do Guia Ruby on Rails para estilo e convenções.

Se, por qualquer motivo, você encontrar algo para consertar, mas não conseguir consertá-lo, por favor abra uma issue no nosso Guia.

E por último, mas não menos importante, qualquer tipo de discussão sobre a documentação do Ruby on Rails é muito bem vinda na forum oficial do Ruby on Rails e nas issues do Guia em português.


dark theme icon