aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source/getting_started.md
diff options
context:
space:
mode:
Diffstat (limited to 'guides/source/getting_started.md')
-rw-r--r--guides/source/getting_started.md328
1 files changed, 164 insertions, 164 deletions
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
index 226c3dce14..d39263a086 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -75,9 +75,9 @@ h4. Installing Rails
To install Rails, use the +gem install+ command provided by RubyGems:
-<shell>
+```shell
# gem install rails
-</shell>
+```
TIP. A number of tools exist to help you quickly install Ruby and Ruby
on Rails on your system. Windows users can use "Rails
@@ -86,9 +86,9 @@ Installer":http://railsinstaller.org, while Mac OS X users can use
To verify that you have everything installed correctly, you should be able to run the following:
-<shell>
+```shell
$ rails --version
-</shell>
+```
If it says something like "Rails 3.2.3" you are ready to continue.
@@ -98,9 +98,9 @@ Rails comes with a number of generators that are designed to make your developme
To use this generator, open a terminal, navigate to a directory where you have rights to create files, and type:
-<shell>
+```shell
$ rails new blog
-</shell>
+```
This will create a Rails application called Blog in a directory called blog and install the gem dependencies that are already mentioned in +Gemfile+ using +bundle install+.
@@ -109,9 +109,9 @@ application builder accepts by running +rails new -h+.
After you create the blog application, switch to its folder to continue work directly in that application:
-<shell>
+```shell
$ cd blog
-</shell>
+```
The +rails new blog+ command we ran above created a folder in your
working directory called +blog+. The +blog+ directory has a number of
@@ -143,9 +143,9 @@ h4. Starting up the Web Server
You actually have a functional Rails application already. To see it, you need to start a web server on your development machine. You can do this by running:
-<shell>
+```shell
$ rails server
-</shell>
+```
TIP: Compiling CoffeeScript to JavaScript requires a JavaScript runtime and the absence of a runtime will give you an +execjs+ error. Usually Mac OS X and Windows come with a JavaScript runtime installed. Rails adds the +therubyracer+ gem to Gemfile in a commented line for new apps and you can uncomment if you need it. +therubyrhino+ is the recommended runtime for JRuby users and is added by default to Gemfile in apps generated under JRuby. You can investigate about all the supported runtimes at "ExecJS":https://github.com/sstephenson/execjs#readme.
@@ -167,13 +167,13 @@ A view's purpose is to display this information in a human readable format. An i
To create a new controller, you will need to run the "controller" generator and tell it you want a controller called "welcome" with an action called "index", just like this:
-<shell>
+```shell
$ rails generate controller welcome index
-</shell>
+```
Rails will create several files and a route for you.
-<shell>
+```shell
create app/controllers/welcome_controller.rb
route get "welcome/index"
invoke erb
@@ -190,15 +190,15 @@ invoke coffee
create app/assets/javascripts/welcome.js.coffee
invoke scss
create app/assets/stylesheets/welcome.css.scss
-</shell>
+```
Most important of these are of course the controller, located at +app/controllers/welcome_controller.rb+ and the view, located at +app/views/welcome/index.html.erb+.
Open the +app/views/welcome/index.html.erb+ file in your text editor and edit it to contain a single line of code:
-<html>
+```html
<h1>Hello, Rails!</h1>
-</html>
+```
h4. Setting the Application Home Page
@@ -212,7 +212,7 @@ Next, you have to tell Rails where your actual home page is located.
Open the file +config/routes.rb+ in your editor.
-<ruby>
+```ruby
Blog::Application.routes.draw do
get "welcome/index"
@@ -222,13 +222,13 @@ Blog::Application.routes.draw do
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# root :to => "welcome#index"
-</ruby>
+```
This is your application's _routing file_ which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. This file contains many sample routes on commented lines, and one of them actually shows you how to connect the root of your site to a specific controller and action. Find the line beginning with +root :to+ and uncomment it. It should look something like the following:
-<ruby>
+```ruby
root :to => "welcome#index"
-</ruby>
+```
The +root :to => "welcome#index"+ tells Rails to map requests to the root of the application to the welcome controller's index action and +get "welcome/index"+ tells Rails to map requests to "http://localhost:3000/welcome/index":http://localhost:3000/welcome/index to the welcome controller's index action. This was created earlier when you ran the controller generator (+rails generate controller welcome index+).
@@ -258,9 +258,9 @@ This is because there is nowhere inside the routes for the application -- define
To do this, you're going to need to create a route inside +config/routes.rb+ file, on a new line between the +do+ and the +end+ for the +draw+ method:
-<ruby>
+```ruby
get "posts/new"
-</ruby>
+```
This route is a super-simple route: it defines a new route that only responds to +GET+ requests, and that the route is at +posts/new+. But how does it know where to go without the use of the +:to+ option? Well, Rails uses a sensible default here: Rails will assume that you want this route to go to the new action inside the posts controller.
@@ -270,16 +270,16 @@ With the route defined, requests can now be made to +/posts/new+ in the applicat
This error is happening because this route need a controller to be defined. The route is attempting to find that controller so it can serve the request, but with the controller undefined, it just can't do that. The solution to this particular problem is simple: you need to create a controller called +PostsController+. You can do this by running this command:
-<shell>
+```shell
$ rails g controller posts
-</shell>
+```
If you open up the newly generated +app/controllers/posts_controller.rb+ you'll see a fairly empty controller:
-<ruby>
+```ruby
class PostsController < ApplicationController
end
-</ruby>
+```
A controller is simply a class that is defined to inherit from +ApplicationController+. It's inside this class that you'll define methods that will become the actions for this controller. These actions will perform CRUD operations on the posts within our system.
@@ -291,10 +291,10 @@ This error indicates that Rails cannot find the +new+ action inside the +PostsCo
To manually define an action inside a controller, all you need to do is to define a new method inside the controller. Open +app/controllers/posts_controller.rb+ and inside the +PostsController+ class, define a +new+ method like this:
-<ruby>
+```ruby
def new
end
-</ruby>
+```
With the +new+ method defined in +PostsController+, if you refresh "http://localhost:3000/posts/new":http://localhost:3000/posts/new you'll see another error:
@@ -320,9 +320,9 @@ The simplest template that would work in this case would be one located at +app/
Go ahead now and create a new file at +app/views/posts/new.html.erb+ and write this content in it:
-<erb>
+```erb
<h1>New Post</h1>
-</erb>
+```
When you refresh "http://localhost:3000/posts/new":http://localhost:3000/posts/new you'll now see that the page has a title. The route, controller, action and view are now working harmoniously! It's time to create the form for a new post.
@@ -332,7 +332,7 @@ To create a form within this template, you will use a <em>form
builder</em>. The primary form builder for Rails is provided by a helper
method called +form_for+. To use this method, add this code into +app/views/posts/new.html.erb+:
-<erb>
+```erb
<%= form_for :post do |f| %>
<p>
<%= f.label :title %><br>
@@ -348,7 +348,7 @@ method called +form_for+. To use this method, add this code into +app/views/post
<%= f.submit %>
</p>
<% end %>
-</erb>
+```
If you refresh the page now, you'll see the exact same form as in the example. Building forms in Rails is really just that easy!
@@ -366,15 +366,15 @@ like this is called "create", and so the form should be pointed to that action.
Edit the +form_for+ line inside +app/views/posts/new.html.erb+ to look like this:
-<erb>
+```erb
<%= form_for :post, :url => { :action => :create } do |f| %>
-</erb>
+```
In this example, a +Hash+ object is passed to the +:url+ option. What Rails will do with this is that it will point the form to the +create+ action of the current controller, the +PostsController+, and will send a +POST+ request to that route. For this to work, you will need to add a route to +config/routes.rb+, right underneath the one for "posts/new":
-<ruby>
+```ruby
post "posts" => "posts#create"
-</ruby>
+```
By using the +post+ method rather than the +get+ method, Rails will define a route that will only respond to POST methods. The POST method is the typical method used by forms all over the web.
@@ -388,7 +388,7 @@ h4. Creating posts
To make the "Unknown action" go away, you can define a +create+ action within the +PostsController+ class in +app/controllers/posts_controller.rb+, underneath the +new+ action:
-<ruby>
+```ruby
class PostsController < ApplicationController
def new
end
@@ -397,25 +397,25 @@ class PostsController < ApplicationController
end
end
-</ruby>
+```
If you re-submit the form now, you'll see another familiar error: a template is missing. That's ok, we can ignore that for now. What the +create+ action should be doing is saving our new post to a database.
When a form is submitted, the fields of the form are sent to Rails as _parameters_. These parameters can then be referenced inside the controller actions, typically to perform a particular task. To see what these parameters look like, change the +create+ action to this:
-<ruby>
+```ruby
def create
render :text => params[:post].inspect
end
-</ruby>
+```
The +render+ method here is taking a very simple hash with a key of +text+ and value of +params[:post].inspect+. The +params+ method is the object which represents the parameters (or fields) coming in from the form. The +params+ method returns a +HashWithIndifferentAccess+ object, which allows you to access the keys of the hash using either strings or symbols. In this situation, the only parameters that matter are the ones from the form.
If you re-submit the form one more time you'll now no longer get the missing template error. Instead, you'll see something that looks like the following:
-<ruby>
+```ruby
{"title"=>"First post!", "text"=>"This is my first post."}
-</ruby>
+```
This action is now displaying the parameters for the post that are coming in from the form. However, this isn't really all that helpful. Yes, you can see the parameters but nothing in particular is being done with them.
@@ -426,9 +426,9 @@ a plural name. Rails provides a generator for creating models, which
most Rails developers tend to use when creating new models.
To create the new model, run this command in your terminal:
-<shell>
+```shell
$ rails generate model Post title:string text:text
-</shell>
+```
With that command we told Rails that we want a +Post+ model, together
with a _title_ attribute of type string, and a _text_ attribute
@@ -459,7 +459,7 @@ order that they were created.
If you look in the +db/migrate/20120419084633_create_posts.rb+ file (remember,
yours will have a slightly different name), here's what you'll find:
-<ruby>
+```ruby
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
@@ -470,7 +470,7 @@ class CreatePosts < ActiveRecord::Migration
end
end
end
-</ruby>
+```
The above migration creates a method named +change+ which will be called when you
run this migration. The action defined in this method is also reversible, which
@@ -483,19 +483,19 @@ Migrations":migrations.html guide.
At this point, you can use a rake command to run the migration:
-<shell>
+```shell
$ rake db:migrate
-</shell>
+```
Rails will execute this migration command and tell you it created the Posts
table.
-<shell>
+```shell
== CreatePosts: migrating ====================================================
-- create_table(:posts)
-> 0.0019s
== CreatePosts: migrated (0.0020s) ===========================================
-</shell>
+```
NOTE. Because you're working in the development environment by default, this
command will apply to the database defined in the +development+ section of your
@@ -509,14 +509,14 @@ Back in +posts_controller+, we need to change the +create+ action
to use the new +Post+ model to save the data in the database. Open that file
and change the +create+ action to look like this:
-<ruby>
+```ruby
def create
@post = Post.new(params[:post])
@post.save
redirect_to :action => :show, :id => @post.id
end
-</ruby>
+```
Here's what's going on: every Rails model can be initialized with its
respective attributes, which are automatically mapped to the respective
@@ -535,9 +535,9 @@ If you submit the form again now, Rails will complain about not finding
the +show+ action. That's not very useful though, so let's add the
+show+ action before proceeding. Open +config/routes.rb+ and add the following route:
-<ruby>
+```ruby
get "posts/:id" => "posts#show"
-</ruby>
+```
The special syntax +:id+ tells rails that this route expects an +:id+
parameter, which in our case will be the id of the post. Note that this
@@ -547,11 +547,11 @@ otherwise Rails would not know which action to render.
As we did before, we need to add the +show+ action in the
+posts_controller+ and its respective view.
-<ruby>
+```ruby
def show
@post = Post.find(params[:id])
end
-</ruby>
+```
A couple of things to note. We use +Post.find+ to find the post we're
interested in. We also use an instance variable (prefixed by +@+) to
@@ -561,7 +561,7 @@ variables to the view.
Now, create a new file +app/view/posts/show.html.erb+ with the following
content:
-<erb>
+```erb
<p>
<strong>Title:</strong>
<%= @post.title %>
@@ -571,7 +571,7 @@ content:
<strong>Text:</strong>
<%= @post.text %>
</p>
-</erb>
+```
Finally, if you now go to
"http://localhost:3000/posts/new":http://localhost:3000/posts/new you'll
@@ -584,21 +584,21 @@ h4. Listing all posts
We still need a way to list all our posts, so let's do that. As usual,
we'll need a route placed into +config/routes.rb+:
-<ruby>
+```ruby
get "posts" => "posts#index"
-</ruby>
+```
And an action for that route inside the +PostsController+ in the +app/controllers/posts_controller.rb+ file:
-<ruby>
+```ruby
def index
@posts = Post.all
end
-</ruby>
+```
And then finally a view for this action, located at +app/views/posts/index.html.erb+:
-<erb>
+```erb
<h1>Listing posts</h1>
<table>
@@ -614,7 +614,7 @@ And then finally a view for this action, located at +app/views/posts/index.html.
</tr>
<% end %>
</table>
-</erb>
+```
Now if you go to +http://localhost:3000/posts+ you will see a list of all the posts that you have created.
@@ -625,10 +625,10 @@ navigate through pages.
Open +app/views/welcome/index.html.erb+ and modify it as follows:
-<ruby>
+```ruby
<h1>Hello, Rails!</h1>
<%= link_to "My Blog", :controller => "posts" %>
-</ruby>
+```
The +link_to+ method is one of Rails' built-in view helpers. It creates a
hyperlink based on text to display and where to go - in this case, to the path
@@ -636,23 +636,23 @@ for posts.
Let's add links to the other views as well, starting with adding this "New Post" link to +app/views/posts/index.html.erb+, placing it above the +&lt;table&gt;+ tag:
-<erb>
+```erb
<%= link_to 'New post', :action => :new %>
-</erb>
+```
This link will allow you to bring up the form that lets you create a new post. You should also add a link to this template -- +app/views/posts/new.html.erb+ -- to go back to the +index+ action. Do this by adding this underneath the form in this template:
-<erb>
+```erb
<%= form_for :post do |f| %>
...
<% end %>
<%= link_to 'Back', :action => :index %>
-</erb>
+```
Finally, add another link to the +app/views/posts/show.html.erb+ template to go back to the +index+ action as well, so that people who are viewing a single post can go back and view the whole list again:
-<erb>
+```erb
<p>
<strong>Title:</strong>
<%= @post.title %>
@@ -664,7 +664,7 @@ Finally, add another link to the +app/views/posts/show.html.erb+ template to go
</p>
<%= link_to 'Back', :action => :index %>
-</erb>
+```
TIP: If you want to link to an action in the same controller, you don't
need to specify the +:controller+ option, as Rails will use the current
@@ -678,10 +678,10 @@ h4. Allowing the update of fields
The model file, +app/models/post.rb+ is about as simple as it can get:
-<ruby>
+```ruby
class Post < ActiveRecord::Base
end
-</ruby>
+```
There isn't much to this file - but note that the +Post+ class inherits from
+ActiveRecord::Base+. Active Record supplies a great deal of functionality to
@@ -692,11 +692,11 @@ and the ability to relate multiple models to one another.
Rails includes methods to help you secure some of your model fields.
Open the +app/models/post.rb+ file and edit it:
-<ruby>
+```ruby
class Post < ActiveRecord::Base
attr_accessible :text, :title
end
-</ruby>
+```
This change will ensure that all changes made through HTML forms can edit the content of the text and title fields.
It will not be possible to define any other field value through forms. You can still define them by calling the `field=` method of course.
@@ -707,14 +707,14 @@ h4. Adding Some Validation
Rails includes methods to help you validate the data that you send to models.
Open the +app/models/post.rb+ file and edit it:
-<ruby>
+```ruby
class Post < ActiveRecord::Base
attr_accessible :text, :title
validates :title, :presence => true,
:length => { :minimum => 5 }
end
-</ruby>
+```
These changes will ensure that all posts have a title that is at least five characters long.
Rails can validate a variety of conditions in a model, including the presence or uniqueness of columns, their
@@ -729,7 +729,7 @@ inside the +create+ action. If +@post.save+ fails in this situation, we need to
show the form back to the user. To do this, change the +new+ and +create+
actions inside +app/controllers/posts_controller.rb+ to these:
-<ruby>
+```ruby
def new
@post = Post.new
end
@@ -743,7 +743,7 @@ def create
render 'new'
end
end
-</ruby>
+```
The +new+ action is now creating a new instance variable called +@post+, and
you'll see why that is in just a few moments.
@@ -758,7 +758,7 @@ form, but that's not very useful. You need to tell the user that
something went wrong. To do that, you'll modify
+app/views/posts/new.html.erb+ to check for error messages:
-<erb>
+```erb
<%= form_for :post, :url => { :action => :create } do |f| %>
<% if @post.errors.any? %>
<div id="errorExplanation">
@@ -787,7 +787,7 @@ something went wrong. To do that, you'll modify
<% end %>
<%= link_to 'Back', :action => :index %>
-</erb>
+```
A few things are going on. We check if there are any errors with
+@post.errors.any?+, and in that case we show a list of all
@@ -819,23 +819,23 @@ The first step we'll take is adding a +edit+ action to
Start by adding a route to +config/routes.rb+:
-<ruby>
+```ruby
get "posts/:id/edit" => "posts#edit"
-</ruby>
+```
And then add the controller action:
-<ruby>
+```ruby
def edit
@post = Post.find(params[:id])
end
-</ruby>
+```
The view will contain a form similar to the one we used when creating
new posts. Create a file called +app/views/posts/edit.html.erb+ and make
it look as follows:
-<erb>
+```erb
<h1>Editing post</h1>
<%= form_for :post, :url => { :action => :update, :id => @post.id },
@@ -867,7 +867,7 @@ it look as follows:
<% end %>
<%= link_to 'Back', :action => :index %>
-</erb>
+```
This time we point the form to the +update+ action, which is not defined yet
but will be very soon.
@@ -881,13 +881,13 @@ TIP: By default forms built with the +form_for_ helper are sent via +POST+.
Next, we need to add the +update+ action. The file
+config/routes.rb+ will need just one more line:
-<ruby>
+```ruby
put "posts/:id" => "posts#update"
-</ruby>
+```
And then create the +update+ action in +app/controllers/posts_controller.rb+:
-<ruby>
+```ruby
def update
@post = Post.find(params[:id])
@@ -897,7 +897,7 @@ def update
render 'edit'
end
end
-</ruby>
+```
The new method, +update_attributes+, is used when you want to update a record
that already exists, and it accepts a hash containing the attributes
@@ -913,7 +913,7 @@ Finally, we want to show a link to the +edit+ action in the list of all the
posts, so let's add that now to +app/views/posts/index.html.erb+ to make it
appear next to the "Show" link:
-<erb>
+```erb
<table>
<tr>
@@ -932,19 +932,19 @@ appear next to the "Show" link:
</tr>
<% end %>
</table>
-</erb>
+```
And we'll also add one to the +app/views/posts/show.html.erb+ template as well,
so that there's also an "Edit" link on a post's page. Add this at the bottom of
the template:
-<erb>
+```erb
...
<%= link_to 'Back', :action => :index %>
| <%= link_to 'Edit', :action => :edit, :id => @post.id %>
-</erb>
+```
And here's how our app looks so far:
@@ -956,7 +956,7 @@ h4. Using partials to clean up duplication in views
+partials+ are what Rails uses to remove duplication in views. Here's a
simple example:
-<erb>
+```erb
# app/views/user/show.html.erb
<h1><%= @user.name %></h1>
@@ -968,7 +968,7 @@ simple example:
<%= @user.location %>
<%= @user.about_me %>
-</erb>
+```
The +users/show+ template will automatically include the content of the
+users/_user_details+ template. Note that partials are prefixed by an underscore,
@@ -985,7 +985,7 @@ using a partial.
Create a new file +app/views/posts/_form.html.erb+ with the following
content:
-<erb>
+```erb
<%= form_for @post do |f| %>
<% if @post.errors.any? %>
<div id="errorExplanation">
@@ -1012,7 +1012,7 @@ content:
<%= f.submit %>
</p>
<% end %>
-</erb>
+```
Everything except for the +form_for+ declaration remained the same.
How +form_for+ can figure out the right +action+ and +method+ attributes
@@ -1020,23 +1020,23 @@ when building the form will be explained in just a moment. For now, let's update
+app/views/posts/new.html.erb+ view to use this new partial, rewriting it
completely:
-<erb>
+```erb
<h1>New post</h1>
<%= render 'form' %>
<%= link_to 'Back', :action => :index %>
-</erb>
+```
Then do the same for the +app/views/posts/edit.html.erb+ view:
-<erb>
+```erb
<h1>Edit post</h1>
<%= render 'form' %>
<%= link_to 'Back', :action => :index %>
-</erb>
+```
Point your browser to "http://localhost:3000/posts/new":http://localhost:3000/posts/new and
try creating a new post. Everything still works. Now try editing the
@@ -1061,7 +1061,7 @@ defined the route for the index action.
However, we don't have a +post_path+ yet, which is the reason why we
received an error before.
-<shell>
+```shell
# rake routes
posts GET /posts(.:format) posts#index
@@ -1071,14 +1071,14 @@ posts_new GET /posts/new(.:format) posts#new
GET /posts/:id/edit(.:format) posts#edit
PUT /posts/:id(.:format) posts#update
root / welcome#index
-</shell>
+```
To fix this, open +config/routes.rb+ and modify the +get "posts/:id"+
line like this:
-<ruby>
+```ruby
get "posts/:id" => "posts#show", :as => :post
-</ruby>
+```
The +:as+ option tells the +get+ method that we want to make routing helpers
called +post_url+ and +post_path+ available to our application. These are
@@ -1094,30 +1094,30 @@ We're now ready to cover the "D" part of CRUD, deleting posts from the
database. Following the REST convention, we're going to add a route for
deleting posts to +config/routes.rb+:
-<ruby>
+```ruby
delete "posts/:id" => "posts#destroy"
-</ruby>
+```
The +delete+ routing method should be used for routes that destroy
resources. If this was left as a typical +get+ route, it could be possible for
people to craft malicious URLs like this:
-<html>
+```html
<a href='http://yoursite.com/posts/1/destroy'>look at this cat!</a>
-</html>
+```
We use the +delete+ method for destroying resources, and this route is mapped to
the +destroy+ action inside +app/controllers/posts_controller.rb+, which doesn't exist yet, but is
provided below:
-<ruby>
+```ruby
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to :action => :index
end
-</ruby>
+```
You can call +destroy+ on Active Record objects when you want to delete
them from the database. Note that we don't need to add a view for this
@@ -1127,7 +1127,7 @@ Finally, add a 'destroy' link to your +index+ action template
(+app/views/posts/index.html.erb) to wrap everything
together.
-<erb>
+```erb
<h1>Listing Posts</h1>
<table>
<tr>
@@ -1148,7 +1148,7 @@ together.
</tr>
<% end %>
</table>
-</erb>
+```
Here we're using +link_to+ in a different way. We wrap the
+:action+ and +:id+ attributes in a hash so that we can pass those two keys in
@@ -1172,7 +1172,7 @@ We've now covered all the CRUD actions of a REST app. We did so by
declaring separate routes with the appropriate verbs into
+config/routes.rb+. Here's how that file looks so far:
-<ruby>
+```ruby
get "posts" => "posts#index"
get "posts/new"
post "posts" => "posts#create"
@@ -1180,26 +1180,26 @@ get "posts/:id" => "posts#show", :as => :post
get "posts/:id/edit" => "posts#edit"
put "posts/:id" => "posts#update"
delete "posts/:id" => "posts#destroy"
-</ruby>
+```
That's a lot to type for covering a single *resource*. Fortunately,
Rails provides a +resources+ method which can be used to declare a
standard REST resource. Here's how +config/routes.rb+ looks after the
cleanup:
-<ruby>
+```ruby
Blog::Application.routes.draw do
resources :posts
root :to => "welcome#index"
end
-</ruby>
+```
If you run +rake routes+, you'll see that all the routes that we
declared before are still available:
-<shell>
+```shell
# rake routes
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
@@ -1209,7 +1209,7 @@ edit_post GET /posts/:id/edit(.:format) posts#edit
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
root / welcome#index
-</shell>
+```
Also, if you go through the motions of creating, updating and deleting
posts the app still works as before.
@@ -1230,9 +1230,9 @@ We're going to see the same generator that we used before when creating
the +Post+ model. This time we'll create a +Comment+ model to hold
reference of post comments. Run this command in your terminal:
-<shell>
+```shell
$ rails generate model Comment commenter:string body:text post:references
-</shell>
+```
This command will generate four files:
@@ -1244,12 +1244,12 @@ This command will generate four files:
First, take a look at +comment.rb+:
-<ruby>
+```ruby
class Comment < ActiveRecord::Base
belongs_to :post
attr_accessible :body, :commenter
end
-</ruby>
+```
This is very similar to the +post.rb+ model that you saw earlier. The difference
is the line +belongs_to :post+, which sets up an Active Record _association_.
@@ -1258,7 +1258,7 @@ You'll learn a little about associations in the next section of this guide.
In addition to the model, Rails has also made a migration to create the
corresponding database table:
-<ruby>
+```ruby
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
@@ -1272,27 +1272,27 @@ class CreateComments < ActiveRecord::Migration
add_index :comments, :post_id
end
end
-</ruby>
+```
The +t.references+ line sets up a foreign key column for the association between
the two models. And the +add_index+ line sets up an index for this association
column. Go ahead and run the migration:
-<shell>
+```shell
$ rake db:migrate
-</shell>
+```
Rails is smart enough to only execute the migrations that have not already been
run against the current database, so in this case you will just see:
-<shell>
+```shell
== CreateComments: migrating =================================================
-- create_table(:comments)
-> 0.0008s
-- add_index(:comments, :post_id)
-> 0.0003s
== CreateComments: migrated (0.0012s) ========================================
-</shell>
+```
h4. Associating Models
@@ -1307,22 +1307,22 @@ In fact, this is very close to the syntax that Rails uses to declare this
association. You've already seen the line of code inside the Comment model that
makes each comment belong to a Post:
-<ruby>
+```ruby
class Comment < ActiveRecord::Base
belongs_to :post
end
-</ruby>
+```
You'll need to edit the +post.rb+ file to add the other side of the association:
-<ruby>
+```ruby
class Post < ActiveRecord::Base
validates :title, :presence => true,
:length => { :minimum => 5 }
has_many :comments
end
-</ruby>
+```
These two declarations enable a good bit of automatic behavior. For example, if
you have an instance variable +@post+ containing a post, you can retrieve all
@@ -1337,11 +1337,11 @@ As with the +welcome+ controller, we will need to add a route so that Rails know
where we would like to navigate to see +comments+. Open up the
+config/routes.rb+ file again, and edit it as follows:
-<ruby>
+```ruby
resources :posts do
resources :comments
end
-</ruby>
+```
This creates +comments+ as a _nested resource_ within +posts+. This is another
part of capturing the hierarchical relationship that exists between posts and
@@ -1355,9 +1355,9 @@ h4. Generating a Controller
With the model in hand, you can turn your attention to creating a matching
controller. Again, we'll use the same generator we used before:
-<shell>
+```shell
$ rails generate controller Comments
-</shell>
+```
This creates six files and one empty directory:
@@ -1379,7 +1379,7 @@ spam comments when they arrive.
So first, we'll wire up the Post show template
(+/app/views/posts/show.html.erb+) to let us make a new comment:
-<erb>
+```erb
<p>
<strong>Title:</strong>
<%= @post.title %>
@@ -1407,7 +1407,7 @@ So first, we'll wire up the Post show template
<%= link_to 'Edit Post', edit_post_path(@post) %> |
<%= link_to 'Back to Posts', posts_path %>
-</erb>
+```
This adds a form on the +Post+ show page that creates a new comment by
calling the +CommentsController+ +create+ action. The +form_for+ call here uses
@@ -1415,7 +1415,7 @@ an array, which will build a nested route, such as +/posts/1/comments+.
Let's wire up the +create+:
-<ruby>
+```ruby
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@@ -1423,7 +1423,7 @@ class CommentsController < ApplicationController
redirect_to post_path(@post)
end
end
-</ruby>
+```
You'll see a bit more complexity here than you did in the controller for posts.
That's a side-effect of the nesting that you've set up. Each request for a
@@ -1441,7 +1441,7 @@ using the +post_path(@post)+ helper. As we have already seen, this calls the
template. This is where we want the comment to show, so let's add that to the
+app/views/posts/show.html.erb+.
-<erb>
+```erb
<p>
<strong>Title:</strong>
<%= @post.title %>
@@ -1482,7 +1482,7 @@ template. This is where we want the comment to show, so let's add that to the
<%= link_to 'Edit Post', edit_post_path(@post) %> |
<%= link_to 'Back to Posts', posts_path %>
-</erb>
+```
Now you can add posts and comments to your blog and have them show up in the
right places.
@@ -1501,7 +1501,7 @@ First, we will make a comment partial to extract showing all the comments for th
post. Create the file +app/views/comments/_comment.html.erb+ and put the
following into it:
-<erb>
+```erb
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
@@ -1511,12 +1511,12 @@ following into it:
<strong>Comment:</strong>
<%= comment.body %>
</p>
-</erb>
+```
Then you can change +app/views/posts/show.html.erb+ to look like the
following:
-<erb>
+```erb
<p>
<strong>Title:</strong>
<%= @post.title %>
@@ -1547,7 +1547,7 @@ following:
<%= link_to 'Edit Post', edit_post_path(@post) %> |
<%= link_to 'Back to Posts', posts_path %>
-</erb>
+```
This will now render the partial in +app/views/comments/_comment.html.erb+ once
for each comment that is in the +@post.comments+ collection. As the +render+
@@ -1560,7 +1560,7 @@ h4. Rendering a Partial Form
Let us also move that new comment section out to its own partial. Again, you
create a file +app/views/comments/_form.html.erb+ containing:
-<erb>
+```erb
<%= form_for([@post, @post.comments.build]) do |f| %>
<p>
<%= f.label :commenter %><br />
@@ -1574,11 +1574,11 @@ create a file +app/views/comments/_form.html.erb+ containing:
<%= f.submit %>
</p>
<% end %>
-</erb>
+```
Then you make the +app/views/posts/show.html.erb+ look like the following:
-<erb>
+```erb
<p>
<strong>Title:</strong>
<%= @post.title %>
@@ -1594,7 +1594,7 @@ Then you make the +app/views/posts/show.html.erb+ look like the following:
<%= link_to 'Edit Post', edit_post_path(@post) %> |
<%= link_to 'Back to Posts', posts_path %>
-</erb>
+```
The second render just defines the partial template we want to render,
<tt>comments/form</tt>. Rails is smart enough to spot the forward slash in that
@@ -1613,7 +1613,7 @@ in the +CommentsController+.
So first, let's add the delete link in the
+app/views/comments/_comment.html.erb+ partial:
-<erb>
+```erb
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
@@ -1629,14 +1629,14 @@ So first, let's add the delete link in the
:method => :delete,
:data => { :confirm => 'Are you sure?' } %>
</p>
-</erb>
+```
Clicking this new "Destroy Comment" link will fire off a <tt>DELETE
/posts/:id/comments/:id</tt> to our +CommentsController+, which can then use
this to find the comment we want to delete, so let's add a destroy action to our
controller:
-<ruby>
+```ruby
class CommentsController < ApplicationController
def create
@@ -1653,7 +1653,7 @@ class CommentsController < ApplicationController
end
end
-</ruby>
+```
The +destroy+ action will find the post we are looking at, locate the comment
within the <tt>@post.comments</tt> collection, and then remove it from the
@@ -1667,13 +1667,13 @@ Otherwise they would simply occupy space in the database. Rails allows you to
use the +dependent+ option of an association to achieve this. Modify the Post
model, +app/models/post.rb+, as follows:
-<ruby>
+```ruby
class Post < ActiveRecord::Base
validates :title, :presence => true,
:length => { :minimum => 5 }
has_many :comments, :dependent => :destroy
end
-</ruby>
+```
h3. Security
@@ -1692,7 +1692,7 @@ To use the authentication system, we specify it at the top of our
+PostsController+, in this case, we want the user to be authenticated on every
action, except for +index+ and +show+, so we write that:
-<ruby>
+```ruby
class PostsController < ApplicationController
http_basic_authenticate_with :name => "dhh", :password => "secret", :except => [:index, :show]
@@ -1700,12 +1700,12 @@ class PostsController < ApplicationController
def index
@posts = Post.all
# snipped for brevity
-</ruby>
+```
We also only want to allow authenticated users to delete comments, so in the
+CommentsController+ we write:
-<ruby>
+```ruby
class CommentsController < ApplicationController
http_basic_authenticate_with :name => "dhh", :password => "secret", :only => :destroy
@@ -1713,7 +1713,7 @@ class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
# snipped for brevity
-</ruby>
+```
Now if you try to create a new post, you will be greeted with a basic HTTP
Authentication challenge