command_line.md 24.2 KB
Newer Older
1
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.**
X
Xavier Noria 已提交
2

S
Steve Klabnik 已提交
3 4
The Rails Command Line
======================
5

6 7
After reading this guide, you will know:

8 9 10 11
* How to create a Rails application.
* How to generate models, controllers, database migrations, and unit tests.
* How to start a development server.
* How to experiment with objects through an interactive shell.
12

13
--------------------------------------------------------------------------------
14

15
NOTE: This tutorial assumes you have basic Rails knowledge from reading the [Getting Started with Rails Guide](getting_started.html).
16

17 18
Command Line Basics
-------------------
19 20 21

There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:

22 23
* `rails console`
* `rails server`
24
* `bin/rails`
25 26 27
* `rails generate`
* `rails dbconsole`
* `rails new app_name`
28

29
All commands can run with `-h` or `--help` to list more information.
V
Vishnu Atrai 已提交
30

31 32
Let's create a simple Rails application to step through each of these commands in context.

33
### `rails new`
34

35
The first thing we'll want to do is create a new Rails application by running the `rails new` command after installing Rails.
36

37
INFO: You can install the rails gem by typing `gem install rails`, if you don't have it already.
38

P
Prem Sichanugrist 已提交
39
```bash
40
$ rails new commandsapp
41
     create
42
     create  README.md
M
Mikel Lindsaar 已提交
43 44
     create  Rakefile
     create  config.ru
45
     create  .gitignore
M
Mikel Lindsaar 已提交
46 47
     create  Gemfile
     create  app
48
     ...
M
Mikel Lindsaar 已提交
49
     create  tmp/cache
50 51
     ...
        run  bundle install
52
```
53 54 55

Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.

56
### `rails server`
57

58
The `rails server` command launches a web server named Puma which comes bundled with Rails. You'll use this any time you want to access your application through a web browser.
59

60
With no further work, `rails server` will run our new shiny Rails app:
61

P
Prem Sichanugrist 已提交
62
```bash
63
$ cd commandsapp
64
$ bin/rails server
65 66
=> Booting Puma
=> Rails 5.0.0 application starting in development on http://0.0.0.0:3000
67
=> Run `rails server -h` for more startup options
68 69 70
Puma starting in single mode...
* Version 3.0.2 (ruby 2.3.0-p0), codename: Plethora of Penguin Pinatas
* Min threads: 5, max threads: 5
71 72
* Environment: development
* Listening on tcp://localhost:3000
73
Use Ctrl-C to stop
74
```
75

76
With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open [http://localhost:3000](http://localhost:3000), you will see a basic Rails app running.
77

78
INFO: You can also use the alias "s" to start the server: `rails s`.
79

80
The server can be run on a different port using the `-p` option. The default development environment can be changed using `-e`.
V
Vijay Dev 已提交
81

P
Prem Sichanugrist 已提交
82
```bash
83
$ bin/rails server -e production -p 4000
84
```
V
Vijay Dev 已提交
85

86
The `-b` option binds Rails to the specified IP, by default it is localhost. You can run a server as a daemon by passing a `-d` option.
87

88
### `rails generate`
89

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

92
INFO: You can also use the alias "g" to invoke the generator command: `rails g`.
93

P
Prem Sichanugrist 已提交
94
```bash
95
$ bin/rails generate
V
Vijay Dev 已提交
96
Usage: rails generate GENERATOR [args] [options]
97 98 99 100

...
...

M
Mikel Lindsaar 已提交
101
Please choose a generator below.
102

M
Mikel Lindsaar 已提交
103
Rails:
104
  assets
M
Mikel Lindsaar 已提交
105 106 107 108
  controller
  generator
  ...
  ...
109
```
110 111 112

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

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

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

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

P
Prem Sichanugrist 已提交
119
```bash
120
$ bin/rails generate controller
V
Vijay Dev 已提交
121
Usage: rails generate controller NAME [action action] [options]
122 123 124 125

...
...

126 127 128
Description:
    ...

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

    ...

133
Example:
134
    `rails generate controller CreditCards open debit credit close`
135

136
    Credit card controller with URLs like /credit_cards/debit.
137
        Controller: app/controllers/credit_cards_controller.rb
138 139 140
        Test:       test/controllers/credit_cards_controller_test.rb
        Views:      app/views/credit_cards/debit.html.erb [...]
        Helper:     app/helpers/credit_cards_helper.rb
141
```
142

143
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.
144

P
Prem Sichanugrist 已提交
145
```bash
146
$ bin/rails generate controller Greetings hello
147
     create  app/controllers/greetings_controller.rb
148
      route  get "greetings/hello"
M
Mikel Lindsaar 已提交
149 150 151
     invoke  erb
     create    app/views/greetings
     create    app/views/greetings/hello.html.erb
V
Vijay Dev 已提交
152
     invoke  test_unit
M
Mike Moore 已提交
153
     create    test/controllers/greetings_controller_test.rb
M
Mikel Lindsaar 已提交
154 155
     invoke  helper
     create    app/helpers/greetings_helper.rb
156
     invoke  assets
157
     invoke    coffee
158
     create      app/assets/javascripts/greetings.coffee
159
     invoke    scss
160
     create      app/assets/stylesheets/greetings.scss
161
```
162

163
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.
164

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

167
```ruby
P
Pratik Naik 已提交
168
class GreetingsController < ApplicationController
169
  def hello
M
Mikel Lindsaar 已提交
170
    @message = "Hello, how are you today?"
171 172
  end
end
173
```
174

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

177
```erb
178 179
<h1>A Greeting for You!</h1>
<p><%= @message %></p>
180
```
181

182
Fire up your server using `rails server`.
183

P
Prem Sichanugrist 已提交
184
```bash
185
$ bin/rails server
186
=> Booting Puma...
187
```
188

189
The URL will be [http://localhost:3000/greetings/hello](http://localhost:3000/greetings/hello).
190

191
INFO: 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.
192

V
Vijay Dev 已提交
193
Rails comes with a generator for data models too.
194

P
Prem Sichanugrist 已提交
195
```bash
196
$ bin/rails generate model
197 198
Usage:
  rails generate model NAME [field[:type][:index] field[:type][:index]] [options]
199 200 201

...

Y
Yves Senn 已提交
202
Active Record options:
203 204
      [--migration]            # Indicates when to generate migration
                               # Default: true
205

206
...
207

208 209
Description:
    Create rails files for model generator.
210
```
211

212
NOTE: For a list of available field types for the `type` parameter, refer to the [API documentation](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column) for the add_column method for the `SchemaStatements` module. The `index` parameter generates a corresponding index for the column.
213

214
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.
215

M
Mikel Lindsaar 已提交
216
We will set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.
217

P
Prem Sichanugrist 已提交
218
```bash
219
$ bin/rails generate scaffold HighScore game:string score:integer
220
    invoke  active_record
221
    create    db/migrate/20130717151933_create_high_scores.rb
222
    create    app/models/high_score.rb
223
    invoke    test_unit
M
Mike Moore 已提交
224
    create      test/models/high_score_test.rb
225
    create      test/fixtures/high_scores.yml
226 227
    invoke  resource_route
     route    resources :high_scores
228 229 230 231 232 233 234 235 236 237
    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
M
Mike Moore 已提交
238
    create      test/controllers/high_scores_controller_test.rb
239 240
    invoke    helper
    create      app/helpers/high_scores_helper.rb
241 242 243
    invoke    jbuilder
    create      app/views/high_scores/index.json.jbuilder
    create      app/views/high_scores/show.json.jbuilder
244 245
    invoke  assets
    invoke    coffee
246
    create      app/assets/javascripts/high_scores.coffee
247
    invoke    scss
248
    create      app/assets/stylesheets/high_scores.scss
249
    invoke  scss
250
   identical    app/assets/stylesheets/scaffolds.scss
251
```
252

253
The generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the `high_scores` table and fields), takes care of the route for the **resource**, and new tests for everything.
254

255
The migration requires that we **migrate**, that is, run some Ruby code (living in that `20130717151933_create_high_scores.rb`) 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 bin/rails in-depth in a little while.
256

P
Prem Sichanugrist 已提交
257
```bash
258
$ bin/rails db:migrate
M
Mikel Lindsaar 已提交
259 260
==  CreateHighScores: migrating ===============================================
-- create_table(:high_scores)
261 262
   -> 0.0017s
==  CreateHighScores: migrated (0.0019s) ======================================
263
```
264

265 266 267 268 269 270 271
INFO: 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](http://guides.rubyonrails.org/testing.html) for an in-depth 
look at unit testing.
272

273
Let's see the interface Rails created for us.
274

P
Prem Sichanugrist 已提交
275
```bash
276
$ bin/rails server
277
```
278

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

281
### `rails console`
282

283
The `console` command lets you interact with your Rails application from the command line. On the underside, `rails console` uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.
284

285
INFO: You can also use the alias "c" to invoke the console: `rails c`.
286

287
You can specify the environment in which the `console` command should operate.
288

P
Prem Sichanugrist 已提交
289
```bash
290
$ bin/rails console staging
291
```
292

293
If you wish to test out some code without changing any data, you can do that by invoking `rails console --sandbox`.
294

P
Prem Sichanugrist 已提交
295
```bash
296
$ bin/rails console --sandbox
297
Loading development environment in sandbox (Rails 5.0.0)
298 299
Any modifications you make will be rolled back on exit
irb(main):001:0>
300
```
301

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
#### The app and helper objects

Inside the `rails console` you have access to the `app` and `helper` instances.

With the `app` method you can access url and path helpers, as well as do requests.

```bash
>> app.root_path
=> "/"

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

With the `helper` method it is possible to access Rails and your application's helpers.

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

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

327
### `rails dbconsole`
328

I
iangilfillan 已提交
329
`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.
330

331
INFO: You can also use the alias "db" to invoke the dbconsole: `rails db`.
332

333
### `rails runner`
334

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

P
Prem Sichanugrist 已提交
337
```bash
338
$ bin/rails runner "Model.long_running_method"
339
```
340

341
INFO: You can also use the alias "r" to invoke the runner: `rails r`.
342

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

P
Prem Sichanugrist 已提交
345
```bash
346
$ bin/rails runner -e staging "Model.long_running_method"
347
```
348

349 350 351 352 353 354
You can even execute ruby code written in a file with runner.

```bash
$ bin/rails runner lib/code_to_be_run.rb
```

355
### `rails destroy`
356

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

359
INFO: You can also use the alias "d" to invoke the destroy command: `rails d`.
A
Andrey Ognevsky 已提交
360

P
Prem Sichanugrist 已提交
361
```bash
362
$ bin/rails generate model Oops
363 364 365 366
      invoke  active_record
      create    db/migrate/20120528062523_create_oops.rb
      create    app/models/oops.rb
      invoke    test_unit
M
Mike Moore 已提交
367
      create      test/models/oops_test.rb
368
      create      test/fixtures/oops.yml
369
```
P
Prem Sichanugrist 已提交
370
```bash
371
$ bin/rails destroy model Oops
372 373 374 375
      invoke  active_record
      remove    db/migrate/20120528062523_create_oops.rb
      remove    app/models/oops.rb
      invoke    test_unit
M
Mike Moore 已提交
376
      remove      test/models/oops_test.rb
377
      remove      test/fixtures/oops.yml
378
```
379

380 381
bin/rails
---------
382

383
Since Rails 5.0+ has rake commands built into the rails executable, `bin/rails` is the new default for running commands.
384

385
You can get a list of bin/rails tasks available to you, which will often depend on your current directory, by typing `bin/rails --help`. Each task has a description, and should help you find the thing you need.
V
Vishnu Atrai 已提交
386

P
Prem Sichanugrist 已提交
387
```bash
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
$ bin/rails --help
Usage: rails COMMAND [ARGS]

The most common rails 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")
...

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 ...
assets:clean[keep]                  Remove old compiled assets
assets:clobber                      Remove compiled assets
assets:environment                  Load asset compile environment
assets:precompile                   Compile all the assets ...
405
...
406 407 408 409 410 411 412 413 414 415 416 417
db:fixtures:load                    Loads fixtures into the ...
db:migrate                          Migrate the database ...
db:migrate:status                   Display status of migrations
db:rollback                         Rolls the schema back to ...
db:schema:cache:clear               Clears a db/schema_cache.dump file
db:schema:cache:dump                Creates a db/schema_cache.dump file
db:schema:dump                      Creates a db/schema.rb file ...
db:schema:load                      Loads a schema.rb file ...
db:seed                             Loads the seed data ...
db:structure:dump                   Dumps the database structure ...
db:structure:load                   Recreates the databases ...
db:version                          Retrieves the current schema ...
418
...
419 420
restart                             Restart app by touching ...
tmp:create                          Creates tmp directories ...
421
```
422
INFO: You can also use `bin/rails -T`  to get the list of tasks.
423

424
### `about`
425

426
`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.
427

P
Prem Sichanugrist 已提交
428
```bash
429
$ bin/rails about
430
About your application's environment
431
Rails version             5.0.0
J
Jon Atack 已提交
432 433
Ruby version              2.2.2 (x86_64-linux)
RubyGems version          2.4.6
434
Rack version              1.6
435
JavaScript Runtime        Node.js (V8)
436
Middleware                Rack::Sendfile, ActionDispatch::Static, ActionDispatch::Executor, #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007ffd131a7c88>, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, Rack::Head, Rack::ConditionalGet, Rack::ETag
437
Application root          /home/foobar/commandsapp
438
Environment               development
439
Database adapter          sqlite3
440
Database schema version   20110805173523
441
```
442

443
### `assets`
444

445
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` task allows for rolling deploys that may still be linking to an old asset while the new assets are being built.
446

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

449
### `db`
450

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

Y
yui-knk 已提交
453
More information about migrations can be found in the [Migrations](active_record_migrations.html) guide.
454

455
### `notes`
456

457
`bin/rails notes` will search through your code for comments beginning with FIXME, OPTIMIZE or TODO. The search is done in files with extension `.builder`, `.rb`, `.rake`, `.yml`, `.yaml`, `.ruby`, `.css`, `.js` and `.erb` for both default and custom annotations.
V
Vijay Dev 已提交
458

P
Prem Sichanugrist 已提交
459
```bash
460
$ bin/rails notes
V
Vijay Dev 已提交
461 462 463 464 465
(in /home/foobar/commandsapp)
app/controllers/admin/users_controller.rb:
  * [ 20] [TODO] any other way to do this?
  * [132] [FIXME] high priority for next deploy

A
Akira Matsuda 已提交
466
app/models/school.rb:
V
Vijay Dev 已提交
467 468
  * [ 13] [OPTIMIZE] refactor this code to make it faster
  * [ 17] [FIXME]
469
```
V
Vijay Dev 已提交
470

R
robertomiranda 已提交
471 472 473 474 475 476
You can add support for new file extensions using `config.annotations.register_extensions` option, which receives a list of the extensions with its corresponding regex to match it up.

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

477
If you are looking for a specific annotation, say FIXME, you can use `bin/rails notes:fixme`. Note that you have to lower case the annotation's name.
478

P
Prem Sichanugrist 已提交
479
```bash
480
$ bin/rails notes:fixme
481 482 483 484
(in /home/foobar/commandsapp)
app/controllers/admin/users_controller.rb:
  * [132] high priority for next deploy

A
Akira Matsuda 已提交
485
app/models/school.rb:
486
  * [ 17]
487
```
488

489
You can also use custom annotations in your code and list them using `bin/rails notes:custom` by specifying the annotation using an environment variable `ANNOTATION`.
V
Vijay Dev 已提交
490

P
Prem Sichanugrist 已提交
491
```bash
492
$ bin/rails notes:custom ANNOTATION=BUG
V
Vijay Dev 已提交
493
(in /home/foobar/commandsapp)
494
app/models/article.rb:
V
Vijay Dev 已提交
495
  * [ 23] Have to fix this one before pushing!
496
```
497

498 499
NOTE. When using specific annotations and custom annotations, the annotation name (FIXME, BUG etc) is not displayed in the output lines.

500
By default, `rails notes` will look in the `app`, `config`, `db`, `lib` and `test` directories. If you would like to search other directories, you can provide them as a comma separated list in an environment variable `SOURCE_ANNOTATION_DIRECTORIES`.
501

P
Prem Sichanugrist 已提交
502
```bash
503
$ export SOURCE_ANNOTATION_DIRECTORIES='spec,vendor'
504
$ bin/rails notes
505
(in /home/foobar/commandsapp)
A
Akira Matsuda 已提交
506
app/models/user.rb:
507
  * [ 35] [FIXME] User should have a subscription at this point
508
spec/models/user_spec.rb:
509
  * [122] [TODO] Verify the user that has a subscription works
510
```
511

512
### `routes`
513

514
`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.
515

516
### `test`
517

518
INFO: A good description of unit testing in Rails is given in [A Guide to Testing Rails Applications](testing.html)
519

A
Alex Altair 已提交
520
Rails comes with a test suite called Minitest. Rails owes its stability to the use of tests. The tasks available in the `test:` namespace helps in running the different tests you will hopefully write.
521

522
### `tmp`
523

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

526
The `tmp:` namespaced tasks will help you clear and create the `Rails.root/tmp` directory:
527

528 529 530 531
* `rails tmp:cache:clear` clears `tmp/cache`.
* `rails tmp:sockets:clear` clears `tmp/sockets`.
* `rails tmp:clear` clears all cache and sockets files.
* `rails tmp:create` creates tmp directories for cache, sockets and pids.
532

533
### Miscellaneous
534

535 536 537
* `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.
* `rails secret` will give you a pseudo-random key to use for your session secret.
* `rails time:zones:all` lists all the timezones Rails knows about.
538

V
Vijay Dev 已提交
539
### Custom Rake Tasks
540

541
Custom rake tasks have a `.rake` extension and are placed in
542 543
`Rails.root/lib/tasks`. You can create these custom rake tasks with the
`bin/rails generate task` command.
544

545
```ruby
546
desc "I am short, but comprehensive description for my cool task"
A
Agis Anastasopoulos 已提交
547
task task_name: [:prerequisite_task, :another_task_we_depend_on] do
P
Przemek Hocke 已提交
548
  # All your magic here
549 550
  # Any valid Ruby code is allowed
end
551
```
552

V
Vijay Dev 已提交
553
To pass arguments to your custom rake task:
554

555
```ruby
556 557
task :task_name, [:arg_1] => [:prerequisite_1, :prerequisite_2] do |task, args|
  argument_1 = args.arg_1
558
end
559
```
560 561 562

You can group tasks by placing them in namespaces:

563
```ruby
564
namespace :db do
565 566 567 568 569
  desc "This task does nothing"
  task :nothing do
    # Seriously, nothing
  end
end
570
```
571

V
Vijay Dev 已提交
572
Invocation of the tasks will look like:
573

P
Prem Sichanugrist 已提交
574
```bash
575 576 577
$ bin/rails task_name
$ bin/rails "task_name[value 1]" # entire argument string should be quoted
$ bin/rails db:nothing
578
```
579

580
NOTE: If your need to interact with your application models, perform database queries and so on, your task should depend on the `environment` task, which will load your application code.
581

582 583
The Rails Advanced Command Line
-------------------------------
584

585
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.
586

587
### Rails with Databases and SCM
588 589 590

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.

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

P
Prem Sichanugrist 已提交
593
```bash
594 595 596 597
$ mkdir gitapp
$ cd gitapp
$ git init
Initialized empty Git repository in .git/
598
$ rails new . --git --database=postgresql
599 600 601 602 603 604 605 606 607
      exists
      create  app/controllers
      create  app/helpers
...
...
      create  tmp/cache
      create  tmp/pids
      create  Rakefile
add 'Rakefile'
608 609
      create  README.md
add 'README.md'
V
Vijay Dev 已提交
610 611
      create  app/controllers/application_controller.rb
add 'app/controllers/application_controller.rb'
612 613 614 615
      create  app/helpers/application_helper.rb
...
      create  log/test.log
add 'log/test.log'
616
```
617

618
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:
619

P
Prem Sichanugrist 已提交
620
```bash
621
$ cat config/database.yml
622
# PostgreSQL. Versions 9.1 and up are supported.
623
#
624 625 626 627 628 629
# Install the pg driver:
#   gem install pg
# On OS X with Homebrew:
#   gem install pg -- --with-pg-config=/usr/local/bin/pg_config
# On OS X with MacPorts:
#   gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
630
# On Windows:
631
#   gem install pg
632 633
#       Choose the win32 build.
#       Install PostgreSQL and put its /bin directory on your path.
634 635 636 637
#
# Configure Using Gemfile
# gem 'pg'
#
638 639 640 641
development:
  adapter: postgresql
  encoding: unicode
  database: gitapp_development
642
  pool: 5
643 644 645 646
  username: gitapp
  password:
...
...
647
```
648

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

651
NOTE. 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.