A Guide to The Rails Command Line
Rails comes with every command line tool you’ll need to
-
Create a Rails application
-
Generate models, controllers, database migrations, and unit tests
-
Start a development server
-
Mess with objects through an interactive shell
-
Profile and benchmark your new creation
... and much, much more! (Buy now!)
This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.
1. Command Line Basics
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:
-
console
-
server
-
rake
-
generate
-
rails
Let’s create a simple Rails application to step through each of these commands in context.
1.1. rails
The first thing we’ll want to do is create a new Rails application by running the rails command after installing Rails.
You know you need the rails gem installed by typing gem install rails first, right? Okay, okay, just making sure. |
$ rails commandsapp create create app/controllers create app/helpers create app/models ... ... create log/production.log create log/development.log create log/test.log
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.
This output will seem very familiar when we get to the generate command. Creepy foreshadowing! |
1.2. server
Let’s try it! The server command launches a small web server named WEBrick which comes bundled with Ruby. You’ll use this any time you want to view your work through a web browser.
WEBrick isn’t your only option for serving Rails. We’ll get to that in a later section. [XXX: which section] |
Here we’ll flex our server command, which without any prodding of any kind will run our new shiny Rails app:
$ cd commandsapp $ ./script/server => Booting WEBrick... => Rails 2.2.0 application started on http://0.0.0.0:3000 => Ctrl-C to shutdown server; call with --help for options [2008-11-04 10:11:38] INFO WEBrick 1.3.1 [2008-11-04 10:11:38] INFO ruby 1.8.5 (2006-12-04) [i486-linux] [2008-11-04 10:11:38] INFO WEBrick::HTTPServer#start: pid=18994 port=3000
WHOA. With just three commands we whipped up a Rails server listening on port 3000. Go! Go right now to your browser and go to http://localhost:3000. I’ll wait.
See? Cool! It doesn’t do much yet, but we’ll change that.
1.3. generate
The generate command uses templates to create a whole lot of things. You can always find out what’s available by running generate by itself. Let’s do that:
$ ./script/generate Usage: ./script/generate generator [options] [args] ... ... Installed Generators Builtin: controller, integration_test, mailer, migration, model, observer, performance_test, plugin, resource, scaffold, session_migration ... ...
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 for you — necessary for the darn thing to work, but not necessary for you to spend time writing. That’s what we have computers for, right?
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 ./script/server --help. |
$ ./script/generate controller Usage: ./script/generate controller ControllerName [options] ... ... Example: `./script/generate controller CreditCard open debit credit close` Credit card controller with URLs like /credit_card/debit. Controller: app/controllers/credit_card_controller.rb Views: app/views/credit_card/debit.html.erb [...] Helper: app/helpers/credit_card_helper.rb Test: test/functional/credit_card_controller_test.rb Modules Example: `./script/generate controller 'admin/credit_card' suspend late_fee` Credit card admin controller with URLs /admin/credit_card/suspend. Controller: app/controllers/admin/credit_card_controller.rb Views: app/views/admin/credit_card/debit.html.erb [...] Helper: app/helpers/admin/credit_card_helper.rb Test: test/functional/admin/credit_card_controller_test.rb
Ah, 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.
$ ./script/generate controller Greeting hello exists app/controllers/ exists app/helpers/ create app/views/greeting exists test/functional/ create app/controllers/greetings_controller.rb create test/functional/greetings_controller_test.rb create app/helpers/greetings_helper.rb create app/views/greetings/hello.html.erb
Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file.
Let’s check out the controller and modify it a little (in app/controllers/greeting_controller.rb):
class GreetingController < ApplicationController def hello @message = "Hello, how are you today? I am exuberant!" end end
Then the view, to display our nice message (in app/views/greeting/hello.html.erb):
<h1>A Greeting for You!</h1> <p><%= @message %></p>
Deal. Go check it out in your browser. Fire up your server. Remember? ./script/server at the root of your Rails application should do it.
$ ./script/server => Booting WEBrick...
The URL will be http://localhost:3000/greetings/hello. I’ll wait for you to be suitably impressed.
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. |
"What about data, though?", you ask over a cup of coffee. Rails comes with a generator for data models too. Can you guess its generator name?
$ ./script/generate model Usage: ./script/generate model ModelName [field:type, field:type] ... Examples: `./script/generate model account` creates an Account model, test, fixture, and migration: Model: app/models/account.rb Test: test/unit/account_test.rb Fixtures: test/fixtures/accounts.yml Migration: db/migrate/XXX_add_accounts.rb `./script/generate model post title:string body:text published:boolean` creates a Post model with a string title, text body, and published flag.
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.
Let’s set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.
$ ./script/generate scaffold HighScore game:string score:integer exists app/models/ exists app/controllers/ exists app/helpers/ create app/views/high_scores create app/views/layouts/ exists test/functional/ create test/unit/ create public/stylesheets/ create app/views/high_scores/index.html.erb create app/views/high_scores/show.html.erb create app/views/high_scores/new.html.erb create app/views/high_scores/edit.html.erb create app/views/layouts/high_scores.html.erb create public/stylesheets/scaffold.css create app/controllers/high_scores_controller.rb create test/functional/high_scores_controller_test.rb create app/helpers/high_scores_helper.rb route map.resources :high_scores dependency model exists app/models/ exists test/unit/ create test/fixtures/ create app/models/high_score.rb create test/unit/high_score_test.rb create test/fixtures/high_scores.yml exists db/migrate create db/migrate/20081217071914_create_high_scores.rb
Taking it from the top - 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.
The migration requires that we migrate, that is, run some Ruby code (living in that 20081217071914_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 rake db:migrate command. We’ll talk more about Rake in-depth in a little while.
Hey. Install the sqlite3-ruby gem while you’re at it. gem install sqlite3-ruby |
$ rake db:migrate (in /home/commandsapp) == CreateHighScores: migrating =============================================== -- create_table(:high_scores) -> 0.0070s == CreateHighScores: migrated (0.0077s) ======================================
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. We’ll make one in a moment. |
Let’s see the interface Rails created for us. ./script/server; http://localhost:3000/high_scores
We can create new high scores (55,160 on Space Invaders!)
1.4. console
The console command lets you interact with your Rails application from the command line. On the underside, script/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.
1.5. dbconsole
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, PostgreSQL, SQLite and SQLite3.
1.6. plugin
The plugin command simplifies plugin management; think a miniature version of the Gem utility. Let’s walk through installing a plugin. You can call the sub-command discover, which sifts through repositories looking for plugins, or call source to add a specific repository of plugins, or you can specify the plugin location directly.
Let’s say you’re creating a website for a client who wants a small accounting system. Every event having to do with money must be logged, and must never be deleted. Wouldn’t it be great if we could override the behavior of a model to never actually take its record out of the database, but instead, just set a field?
There is such a thing! The plugin we’re installing is called "acts_as_paranoid", and it lets models implement a "deleted_at" column that gets set when you call destroy. Later, when calling find, the plugin will tack on a database check to filter out "deleted" things.
$ ./script/plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_paranoid + ./CHANGELOG + ./MIT-LICENSE ... ...
1.7. runner
runner runs Ruby code in the context of Rails non-interactively. For instance:
$ ./script/runner "Model.long_running_method"
1.8. destroy
Think of destroy as the opposite of generate. It’ll figure out what generate did, and undo it. Believe you-me, the creation of this tutorial used this command many times!
$ ./script/generate model Oops exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/oops.rb create test/unit/oops_test.rb create test/fixtures/oops.yml exists db/migrate create db/migrate/20081221040817_create_oops.rb $ ./script/destroy model Oops notempty db/migrate notempty db rm db/migrate/20081221040817_create_oops.rb rm test/fixtures/oops.yml rm test/unit/oops_test.rb rm app/models/oops.rb notempty test/fixtures notempty test notempty test/unit notempty test notempty app/models notempty app
1.9. about
Check it: 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! about is useful when you need to ask help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.
$ ./script/about About your application's environment Ruby version 1.8.6 (i486-linux) RubyGems version 1.3.1 Rails version 2.2.0 Active Record version 2.2.0 Action Pack version 2.2.0 Active Resource version 2.2.0 Action Mailer version 2.2.0 Active Support version 2.2.0 Edge Rails revision unknown Application root /home/commandsapp Environment development Database adapter sqlite3 Database schema version 20081217073400