aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source
diff options
context:
space:
mode:
Diffstat (limited to 'guides/source')
-rw-r--r--guides/source/3_2_release_notes.textile2
-rw-r--r--guides/source/action_controller_overview.textile9
-rw-r--r--guides/source/action_view_overview.textile24
-rw-r--r--guides/source/active_record_querying.textile15
-rw-r--r--guides/source/asset_pipeline.textile12
-rw-r--r--guides/source/caching_with_rails.textile2
-rw-r--r--guides/source/configuring.textile7
-rw-r--r--guides/source/contributing_to_ruby_on_rails.textile2
-rw-r--r--guides/source/form_helpers.textile2
-rw-r--r--guides/source/getting_started.textile344
-rw-r--r--guides/source/i18n.textile26
-rw-r--r--guides/source/layouts_and_rendering.textile10
-rw-r--r--guides/source/migrations.textile28
-rw-r--r--guides/source/rails_on_rack.textile23
-rw-r--r--guides/source/security.textile2
15 files changed, 400 insertions, 108 deletions
diff --git a/guides/source/3_2_release_notes.textile b/guides/source/3_2_release_notes.textile
index 0f8fea2bf6..3524ea6595 100644
--- a/guides/source/3_2_release_notes.textile
+++ b/guides/source/3_2_release_notes.textile
@@ -299,7 +299,7 @@ end
h5(#actionview_deprecations). Deprecations
-* Passing formats or handlers to render :template and friends like <tt>render :template => "foo.html.erb"</tt> is deprecated. Instead, you can provide :handlers and :formats directly as an options: <tt> render :template => "foo", :formats => [:html, :js], :handlers => :erb</tt>.
+* Passing formats or handlers to render :template and friends like <tt>render :template => "foo.html.erb"</tt> is deprecated. Instead, you can provide :handlers and :formats directly as options: <tt> render :template => "foo", :formats => [:html, :js], :handlers => :erb</tt>.
h4. Sprockets
diff --git a/guides/source/action_controller_overview.textile b/guides/source/action_controller_overview.textile
index 52d134ace5..cc3350819b 100644
--- a/guides/source/action_controller_overview.textile
+++ b/guides/source/action_controller_overview.textile
@@ -148,18 +148,19 @@ In this case, when a user opens the URL +/clients/active+, +params[:status]+ wil
h4. +default_url_options+
-You can set global default parameters that will be used when generating URLs with +default_url_options+. To do this, define a method with that name in your controller:
+You can set global default parameters for URL generation by defining a method called +default_url_options+ in your controller. Such a method must return a hash with the desired defaults, whose keys must be symbols:
<ruby>
class ApplicationController < ActionController::Base
- # The options parameter is the hash passed in to 'url_for'
- def default_url_options(options)
+ def default_url_options
{:locale => I18n.locale}
end
end
</ruby>
-These options will be used as a starting-point when generating URLs, so it's possible they'll be overridden by +url_for+. Because this method is defined in the controller, you can define it on +ApplicationController+ so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.
+These options will be used as a starting point when generating URLs, so it's possible they'll be overridden by the options passed in +url_for+ calls.
+
+If you define +default_url_options+ in +ApplicationController+, as in the example above, it would be used for all URL generation. The method can also be defined in one specific controller, in which case it only affects URLs generated there.
h3. Session
diff --git a/guides/source/action_view_overview.textile b/guides/source/action_view_overview.textile
index 42120e9bad..6649974eea 100644
--- a/guides/source/action_view_overview.textile
+++ b/guides/source/action_view_overview.textile
@@ -550,9 +550,9 @@ Register one or more JavaScript files to be included when symbol is passed to ja
ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
javascript_include_tag :monkey # =>
- <script type="text/javascript" src="/javascripts/head.js"></script>
- <script type="text/javascript" src="/javascripts/body.js"></script>
- <script type="text/javascript" src="/javascripts/tail.js"></script>
+ <script src="/javascripts/head.js"></script>
+ <script src="/javascripts/body.js"></script>
+ <script src="/javascripts/tail.js"></script>
</ruby>
h5. register_stylesheet_expansion
@@ -563,9 +563,9 @@ Register one or more stylesheet files to be included when symbol is passed to +s
ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
stylesheet_link_tag :monkey # =>
- <link href="/stylesheets/head.css" media="screen" rel="stylesheet" type="text/css" />
- <link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" />
- <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" />
+ <link href="/stylesheets/head.css" media="screen" rel="stylesheet" />
+ <link href="/stylesheets/body.css" media="screen" rel="stylesheet" />
+ <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" />
</ruby>
h5. auto_discovery_link_tag
@@ -607,7 +607,7 @@ Returns an html script tag for each of the sources provided. You can pass in the
<ruby>
javascript_include_tag "common" # =>
- <script type="text/javascript" src="/javascripts/common.js"></script>
+ <script src="/javascripts/common.js"></script>
</ruby>
If the application does not use the asset pipeline, to include the jQuery JavaScript library in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well.
@@ -626,7 +626,7 @@ You can also cache multiple JavaScript files into one file, which requires less
<ruby>
javascript_include_tag :all, :cache => true # =>
- <script type="text/javascript" src="/javascripts/all.js"></script>
+ <script src="/javascripts/all.js"></script>
</ruby>
h5. javascript_path
@@ -651,7 +651,7 @@ Returns a stylesheet link tag for the sources specified as arguments. If you don
<ruby>
stylesheet_link_tag "application" # =>
- <link href="/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
+ <link href="/stylesheets/application.css" media="screen" rel="stylesheet" />
</ruby>
You can also include all styles in the stylesheet directory using :all as the source:
@@ -664,7 +664,7 @@ You can also cache multiple stylesheets into one file, which requires less HTTP
<ruby>
stylesheet_link_tag :all, :cache => true
- <link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />
+ <link href="/stylesheets/all.css" media="screen" rel="stylesheet" />
</ruby>
h5. stylesheet_path
@@ -805,7 +805,7 @@ For example, let's say we have a standard application layout, but also a special
<p>This is a special page.</p>
<% content_for :special_script do %>
- <script type="text/javascript">alert('Hello!')</script>
+ <script>alert('Hello!')</script>
<% end %>
</ruby>
@@ -1501,7 +1501,7 @@ javascript_tag "alert('All is good')"
</ruby>
<html>
-<script type="text/javascript">
+<script>
//<![CDATA[
alert('All is good')
//]]>
diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile
index 14d0ba9b28..58eae2ee0f 100644
--- a/guides/source/active_record_querying.textile
+++ b/guides/source/active_record_querying.textile
@@ -539,7 +539,9 @@ And this will give you a single +Order+ object for each date where there are ord
The SQL that would be executed would be something like this:
<sql>
-SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at)
+SELECT date(created_at) as ordered_date, sum(price) as total_price
+FROM orders
+GROUP BY date(created_at)
</sql>
h3. Having
@@ -555,7 +557,10 @@ Order.select("date(created_at) as ordered_date, sum(price) as total_price").grou
The SQL that would be executed would be something like this:
<sql>
-SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at) HAVING sum(price) > 100
+SELECT date(created_at) as ordered_date, sum(price) as total_price
+FROM orders
+GROUP BY date(created_at)
+HAVING sum(price) > 100
</sql>
This will return single order objects for each day, but only those that are ordered more than $100 in a day.
@@ -695,7 +700,7 @@ Optimistic locking allows multiple users to access the same record for edits, an
<strong>Optimistic locking column</strong>
-In order to use optimistic locking, the table needs to have a column called +lock_version+. Each time the record is updated, Active Record increments the +lock_version+ column. If an update request is made with a lower value in the +lock_version+ field than is currently in the +lock_version+ column in the database, the update request will fail with an +ActiveRecord::StaleObjectError+. Example:
+In order to use optimistic locking, the table needs to have a column called +lock_version+ of type integer. Each time the record is updated, Active Record increments the +lock_version+ column. If an update request is made with a lower value in the +lock_version+ field than is currently in the +lock_version+ column in the database, the update request will fail with an +ActiveRecord::StaleObjectError+. Example:
<ruby>
c1 = Client.find(1)
@@ -829,7 +834,7 @@ SELECT categories.* FROM categories
INNER JOIN posts ON posts.category_id = categories.id
</sql>
-Or, in English: "return a Category object for all categories with posts". Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use Category.joins(:post).select("distinct(categories.id)").
+Or, in English: "return a Category object for all categories with posts". Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use Category.joins(:posts).select("distinct(categories.id)").
h5. Joining Multiple Associations
@@ -1004,7 +1009,7 @@ Scopes are also chainable within scopes:
<ruby>
class Post < ActiveRecord::Base
scope :published, -> { where(:published => true) }
- scope :published_and_commented, -> { published.and(self.arel_table[:comments_count].gt(0)) }
+ scope :published_and_commented, -> { published.where("comments_count > 0") }
end
</ruby>
diff --git a/guides/source/asset_pipeline.textile b/guides/source/asset_pipeline.textile
index 982c4aa096..d79eb01ab2 100644
--- a/guides/source/asset_pipeline.textile
+++ b/guides/source/asset_pipeline.textile
@@ -328,9 +328,9 @@ This manifest +app/assets/javascripts/application.js+:
would generate this HTML:
<html>
-<script src="/assets/core.js?body=1" type="text/javascript"></script>
-<script src="/assets/projects.js?body=1" type="text/javascript"></script>
-<script src="/assets/tickets.js?body=1" type="text/javascript"></script>
+<script src="/assets/core.js?body=1"></script>
+<script src="/assets/projects.js?body=1"></script>
+<script src="/assets/tickets.js?body=1"></script>
</html>
The +body+ param is required by Sprockets.
@@ -346,7 +346,7 @@ config.assets.debug = false
When debug mode is off, Sprockets concatenates and runs the necessary preprocessors on all files. With debug mode turned off the manifest above would generate instead:
<html>
-<script src="/assets/application.js" type="text/javascript"></script>
+<script src="/assets/application.js"></script>
</html>
Assets are compiled and cached on the first request after the server is started. Sprockets sets a +must-revalidate+ Cache-Control HTTP header to reduce request overhead on subsequent requests -- on these the browser gets a 304 (Not Modified) response.
@@ -380,8 +380,8 @@ For example this:
generates something like this:
<html>
-<script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js" type="text/javascript"></script>
-<link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen" rel="stylesheet" type="text/css" />
+<script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js"></script>
+<link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen" rel="stylesheet" />
</html>
The fingerprinting behavior is controlled by the setting of +config.assets.digest+ setting in Rails (which defaults to +true+ for production and +false+ for everything else).
diff --git a/guides/source/caching_with_rails.textile b/guides/source/caching_with_rails.textile
index 0e811a2527..12bc32f4e1 100644
--- a/guides/source/caching_with_rails.textile
+++ b/guides/source/caching_with_rails.textile
@@ -92,7 +92,7 @@ INFO: Page caching runs in an after filter. Thus, invalid requests won't generat
h4. Action Caching
-One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow. This is where Action Caching comes in. Action Caching works like Page Caching except for the fact that the incoming web request does go from the webserver to the Rails stack and Action Pack so that before filters can be run on it before the cache is served. This allows authentication and other restriction to be run while still serving the result of the output from a cached copy.
+Page Caching cannot be used for actions that have before filters - for example, pages that require authentication. This is where Action Caching comes in. Action Caching works like Page Caching except the incoming web request hits the Rails stack so that before filters can be run on it before the cache is served. This allows authentication and other restrictions to be run while still serving the result of the output from a cached copy.
Clearing the cache works in a similar way to Page Caching, except you use +expire_action+ instead of +expire_page+.
diff --git a/guides/source/configuring.textile b/guides/source/configuring.textile
index 717654d5d8..1541428af9 100644
--- a/guides/source/configuring.textile
+++ b/guides/source/configuring.textile
@@ -525,6 +525,13 @@ development:
password:
</yaml>
+If you use external connection pool manager, you can disable prepared statements in rails:
+<yaml>
+production:
+ adapter: postgresql
+ prepared_statements: false
+</yaml>
+
h5. Configuring an SQLite3 Database for JRuby Platform
If you choose to use SQLite3 and are using JRuby, your +config/database.yml+ will look a little different. Here's the development section:
diff --git a/guides/source/contributing_to_ruby_on_rails.textile b/guides/source/contributing_to_ruby_on_rails.textile
index d0dbb1555a..fbb3483dae 100644
--- a/guides/source/contributing_to_ruby_on_rails.textile
+++ b/guides/source/contributing_to_ruby_on_rails.textile
@@ -42,7 +42,7 @@ h4. Install Git
Ruby on Rails uses git for source code control. The "git homepage":http://git-scm.com/ has installation instructions. There are a variety of resources on the net that will help you get familiar with git:
-* "Everyday Git":http://www.kernel.org/pub/software/scm/git/docs/everyday.html will teach you just enough about git to get by.
+* "Everyday Git":http://schacon.github.com/git/everyday.html will teach you just enough about git to get by.
* The "PeepCode screencast":https://peepcode.com/products/git on git ($9) is easier to follow.
* "GitHub":http://help.github.com offers links to a variety of git resources.
* "Pro Git":http://progit.org/book/ is an entire book about git with a Creative Commons license.
diff --git a/guides/source/form_helpers.textile b/guides/source/form_helpers.textile
index 8934667c5e..b6420db798 100644
--- a/guides/source/form_helpers.textile
+++ b/guides/source/form_helpers.textile
@@ -89,7 +89,7 @@ form_tag(:controller => "people", :action => "search", :method => "get", :class
# => '<form accept-charset="UTF-8" action="/people/search?method=get&class=nifty_form" method="post">'
</ruby>
-Here, +method+ and +class+ are appended to the query string of the generated URL because you even though you mean to write two hashes, you really only specified one. So you need to tell Ruby which is which by delimiting the first hash (or both) with curly brackets. This will generate the HTML you expect:
+Here, +method+ and +class+ are appended to the query string of the generated URL because even though you mean to write two hashes, you really only specified one. So you need to tell Ruby which is which by delimiting the first hash (or both) with curly brackets. This will generate the HTML you expect:
<ruby>
form_tag({:controller => "people", :action => "search"}, :method => "get", :class => "nifty_form")
diff --git a/guides/source/getting_started.textile b/guides/source/getting_started.textile
index 59b12b49e5..f184004f80 100644
--- a/guides/source/getting_started.textile
+++ b/guides/source/getting_started.textile
@@ -10,7 +10,7 @@ you should be familiar with:
endprologue.
-WARNING. This Guide is based on Rails 3.1. Some of the code shown here will not
+WARNING. This Guide is based on Rails 3.2. Some of the code shown here will not
work in earlier versions of Rails.
WARNING: The Edge version of this guide is currently being re-worked. Please excuse us while we re-arrange the place.
@@ -27,8 +27,8 @@ prerequisites installed:
TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails
3.0. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02
though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults
-on Rails 3.0, so if you want to use Rails 3 with 1.9.x jump on 1.9.2 for smooth
-sailing.
+on Rails 3.0, so if you want to use Rails 3 with 1.9.x jump on 1.9.2 or
+1.9.3 for smooth sailing.
* The "RubyGems":http://rubyforge.org/frs/?group_id=126 packaging system
** If you want to learn more about RubyGems, please read the "RubyGems User Guide":http://docs.rubygems.org/read/book/1
@@ -73,7 +73,8 @@ h3. Creating a New Rails Project
The best way to use this guide is to follow each step as it happens, no code or
step needed to make this example application has been left out, so you can
-literally follow along step by step. You can get the complete code "here":https://github.com/lifo/docrails/tree/master/guides/code/getting_started.
+literally follow along step by step. You can get the complete code
+"here":https://github.com/lifo/docrails/tree/master/guides/code/getting_started.
By following along with this guide, you'll create a Rails project called <tt>blog</tt>, a
(very) simple weblog. Before you can start building the application, you need to
@@ -97,7 +98,7 @@ To verify that you have everything installed correctly, you should be able to ru
$ rails --version
</shell>
-If it says something like "Rails 3.2.2" you are ready to continue.
+If it says something like "Rails 3.2.3" you are ready to continue.
h4. Creating the Blog Application
@@ -111,7 +112,7 @@ $ rails new blog
This will create a Rails application called Blog in a directory called blog.
-TIP: You can see all of the switches that the Rails application builder accepts by running <tt>rails new -h</tt>.
+TIP: You can see all of the command line options that the Rails application builder accepts by running <tt>rails new -h</tt>.
After you create the blog application, switch to its folder to continue work directly in that application:
@@ -225,7 +226,6 @@ h4. Laying down the ground work
The first thing that you are going to need to create a new post within the application is a place to do that. A great place for that would be at +/posts/new+. If you attempt to navigate to that now -- by visiting "http://localhost:3000/posts/new":http://localhost:3000/posts/new -- Rails will give you a routing error:
-
!images/getting_started/routing_error_no_route_matches.png(A routing error, no route matches /posts/new)!
This is because there is nowhere inside the routes for the application -- defined inside +config/routes.rb+ -- that defines this route. By default, Rails has no routes configured at all, and so you must define your routes as you need them.
@@ -240,7 +240,7 @@ This route is a super-simple route: it defines a new route that only responds to
With the route defined, requests can now be made to +/posts/new+ in the application. Navigate to "http://localhost:3000/posts/new":http://localhost:3000/posts/new and you'll see another routing error:
-!images/getting_started/routing_error_no_controller.png(Another routing error, uninitialized constant PostsController)
+!images/getting_started/routing_error_no_controller.png(Another routing error, uninitialized constant PostsController)!
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:
@@ -259,7 +259,7 @@ A controller is simply a class that is defined to inherit from +ApplicationContr
If you refresh "http://localhost:3000/posts/new":http://localhost:3000/posts/new now, you'll get a new error:
-!images/getting_started/unknown_action_new_for_posts.png(Unknown action new for PostsController!)
+!images/getting_started/unknown_action_new_for_posts.png(Unknown action new for PostsController!)!
This error indicates that Rails cannot find the +new+ action inside the +PostsController+ that you just generated. This is because when controllers are generated in Rails they are empty by default, unless you tell it you wanted actions during the generation process.
@@ -272,7 +272,7 @@ end
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:
-!images/getting_started/template_is_missing_posts_new.png(Template is missing for posts/new)
+!images/getting_started/template_is_missing_posts_new.png(Template is missing for posts/new)!
You're getting this error now because Rails expects plain actions like this one to have views associated with them to display their information. With no view available, Rails errors out.
@@ -302,7 +302,9 @@ When you refresh "http://localhost:3000/posts/new":http://localhost:3000/posts/n
h4. The first form
-To create a form within this template, you will use a _form builder_. The primary form builder for Rails is provided by a helper method called +form_for+. To use this method, write this code into +app/views/posts/new.html.erb+:
+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>
<%= form_for :post do |f| %>
@@ -346,7 +348,7 @@ By using the +post+ method rather than the +get+ method, Rails will define a rou
With the form and the route for it defined now, you will be able to fill in the form and then click the submit button to begin the process of creating a new post, so go ahead and do that. When you submit the form, you should see a familiar error:
-!images/getting_started/unknown_action_create_for_posts(Unknown action create for PostsController)!
+!images/getting_started/unknown_action_create_for_posts.png(Unknown action create for PostsController)!
You will now need to create the +create+ action within the +PostsController+ for this to work.
@@ -385,10 +387,30 @@ If you re-submit the form one more time you'll now no longer get the missing tem
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.
+h4. Creating the Post model
+
+Rails uses models to manage database objects, so if you want to save
+data to the database you'll have to create a model. In our blog
+application you want to save posts, so you'll create a +Post+ model.
+
+You can create a model with the following command:
+
+<shell>
+$ rails generate model Post title:string text:text
+</shell>
+
+With that command we told Rails that we want a +Post+ model, which in
+turn should have a title attribute of type string, and a text attribute
+of type text. Rails in turn responded by creating a bunch of files. For
+now, we're only interested in +app/models/post.rb+ and
++db/migrate/20120419084633_create_posts.rb+. The latter is responsible
+for creating the dabase structure, which is what we'll look at next.
+
h4. Running a Migration
-One of the products of the +rails generate scaffold+ command is a _database
-migration_. Migrations are Ruby classes that are designed to make it simple to
+As we've just seen, +rails generate model+ created a _database
+migration_ file inside the +db/migrate+ directory.
+Migrations are Ruby classes that are designed to make it simple to
create and modify database tables. Rails uses rake commands to run migrations,
and it's possible to undo a migration after it's been applied to your database.
Migration filenames include a timestamp to ensure that they're processed in the
@@ -401,9 +423,8 @@ yours will have a slightly different name), here's what you'll find:
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
- t.string :name
t.string :title
- t.text :content
+ t.text :text
t.timestamps
end
@@ -415,7 +436,7 @@ The above migration creates a method named +change+ which will be called when yo
run this migration. The action defined in this method is also reversible, which
means Rails knows how to reverse the change made by this migration, in case you
want to reverse it later. When you run this migration it will create a
-+posts+ table with two string columns and a text column. It also creates two
++posts+ table with one string column and a text column. It also creates two
timestamp fields to allow Rails to track post creation and update times. More
information about Rails migrations can be found in the "Rails Database
Migrations":migrations.html guide.
@@ -442,39 +463,203 @@ command will apply to the database defined in the +development+ section of your
environment, for instance in production, you must explicitly pass it when
invoking the command: <tt>rake db:migrate RAILS_ENV=production</tt>.
-h4. Adding a Link
+h4. Saving data in the controller
+
+Back into +posts_controller+, we need to change the +create+ action
+to use the new +Post+ model to save data in the database. Open that file
+and change the +create+ action to look like the following:
+
+<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 its
+database columns. In the first line we do just that (remember that
++params[:post]+ contains the attributes we're interested in). Then,
++@post.save+ is responsible for saving the model in the database.
+Finally, on the last line we redirect the user to the +show+ action,
+wich we have not defined yet.
-To hook the posts up to the home page you've already created, you can add a link
-to the home page. Open +app/views/welcome/index.html.erb+ and modify it as follows:
+TIP: As we'll see later, +@post.save+ returns a boolean indicating
+wherever the model was saved or not, and you can (and usually do) take
+different actions depending on the result of calling +@post.save+.
+
+h4. Showing posts
+
+Before trying to create a new post, let's add the +show+ action, which
+will be responsible for showing our posts. Open +config/routes.rb+
+and add the following route:
+
+<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
+time we had to specify the actual mapping, +posts#show+ because
+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>
+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
+hold our reference to the post object. We do this because Rails will pass all instance
+variables to the view.
+
+Now, create a new file +app/view/posts/show.html.erb+ with the following
+content:
+
+<erb>
+<p>
+ <strong>Title:</strong>
+ <%= @post.title %>
+</p>
+
+<p>
+ <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
+be able to create a post. Try it!
+
+!images/getting_started/show_action_for_posts.png(Show action for posts)!
+
+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, a controller action, and a view:
+
+<ruby>
+# Add to config/routes.rb
+get "posts" => "posts#index"
+
+# Add to app/controllers/posts_controller.rb
+def index
+ @posts = Post.all
+end
+</ruby>
+
++app/view/posts/index.html.erb+:
+
+<erb>
+<h1>Listing posts</h1>
+
+<table>
+ <tr>
+ <th>Title</th>
+ <th>Text</th>
+ </tr>
+
+<% @posts.each do |post| %>
+ <tr>
+ <td><%= post.title %></td>
+ <td><%= post.text %></td>
+ </tr>
+<% end %>
+</table>
+</erb>
+
+h4. Adding links
+
+You can now create, show, and list posts. But it's difficult to navigate
+through pages, so let's add some links.
+
+Open +app/views/welcome/index.html.erb+ and modify it as follows:
<ruby>
<h1>Hello, Rails!</h1>
-<%= link_to "My Blog", posts_path %>
+<%= 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
for posts.
-h4. Working with Posts in the Browser
+Let's add links to the other views as well.
-Now you're ready to start working with posts. To do that, navigate to
-"http://localhost:3000":http://localhost:3000/ and then click the "My Blog"
-link:
+<erb>
+# app/views/posts/index.html.erb
-!images/posts_index.png(Posts Index screenshot)!
+<h1>Listing posts</h1>
-This is the result of Rails rendering the +index+ view of your posts. There
-aren't currently any posts in the database, but if you click the +New Post+ link
-you can create one. After that, you'll find that you can edit posts, look at
-their details, or destroy them. All of the logic and HTML to handle this was
-built by the single +rails generate scaffold+ command.
+<%= link_to 'New post', :action => :new %>
+
+<table>
+ <tr>
+ <th>Title</th>
+ <th>Text</th>
+ <th></th>
+ </tr>
+
+<% @posts.each do |post| %>
+ <tr>
+ <td><%= post.title %></td>
+ <td><%= post.text %></td>
+ <td><%= link_to 'Show', :action => :show, :id => post.id %></td>
+ </tr>
+<% end %>
+</table>
+
+# app/views/posts/new.html.erb
+
+<%= form_for :post do |f| %>
+ <p>
+ <%= f.label :title %><br>
+ <%= f.text_field :title %>
+ </p>
+
+ <p>
+ <%= f.label :text %><br>
+ <%= f.text_area :text %>
+ </p>
+
+ <p>
+ <%= f.submit %>
+ </p>
+<% end %>
+
+<%= link_to 'Back', :action => :index %>
+
+# app/views/posts/show.html.erb
+
+<p>
+ <strong>Title:</strong>
+ <%= @post.title %>
+</p>
+
+<p>
+ <strong>Text:</strong>
+ <%= @post.text %>
+</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
+controller by default.
TIP: In development mode (which is what you're working in by default), Rails
reloads your application with every browser request, so there's no need to stop
and restart the web server.
-Congratulations, you're riding the rails! Now it's time to see how it all works.
+Congratulations, you're riding the rails! Now it’s time to see how it all works.
h4. The Model
@@ -498,17 +683,102 @@ Open the +app/models/post.rb+ file and edit it:
<ruby>
class Post < ActiveRecord::Base
- validates :name, :presence => true
validates :title, :presence => true,
:length => { :minimum => 5 }
end
</ruby>
-These changes will ensure that all posts have a name and a title, and that the
-title is at least five characters long. Rails can validate a variety of
-conditions in a model, including the presence or uniqueness of columns, their
+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
format, and the existence of associated objects. Validations are covered in detail
-in "Active Record Validations and Callbacks":active_record_validations_callbacks.html#validations-overview
+in "Active Record Validations and
+Callbacks":active_record_validations_callbacks.html#validations-overview
+
+If you open +posts_controller+ again, you'll notice that we don't check
+the result of calling +@post.save+. We need to change its behavior to
+show the form back to the user if any error occur:
+
+<ruby>
+def new
+ @post = Post.new
+end
+
+def create
+ @post = Post.new(params[:post])
+
+ if @post.save
+ redirect_to :action => :show, :id => @post.id
+ else
+ render 'new'
+ end
+end
+</ruby>
+
+Notice that I've also added +@post = Post.new+ to the +new+ action. I'll
+explain why I did that in the next section, for now add that to your
+controller as well.
+
+Also notice that we use +render+ instead of +redirect_to+ when +save+
+returns false. We can use +render+ so that the +@post+ object is passed
+back to the view.
+
+If you reload
+"http://localhost:3000/posts/new":http://localhost:3000/posts/new and
+try to save a post without a title, Rails will send you back to the
+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/index.html.erb+ to check for error messages:
+
+<erb>
+<%= form_for :post do |f| %>
+ <% if @post.errors.any? %>
+ <div id="errorExplanation">
+ <h2><%= pluralize(@post.errors.count, "error") %> prohibited
+ this post from being saved:</h2>
+ <ul>
+ <% @post.errors.full_messages.each do |msg| %>
+ <li><%= msg %></li>
+ <% end %>
+ </ul>
+ </div>
+ <% end %>
+ <p>
+ <%= f.label :title %><br>
+ <%= f.text_field :title %>
+ </p>
+
+ <p>
+ <%= f.label :text %><br>
+ <%= f.text_area :text %>
+ </p>
+
+ <p>
+ <%= f.submit %>
+ </p>
+<% 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
+errors with +@post.errors.full_messages+.
+
++pluralize+ is a rails helper
+that takes a number and a string as its arguments. If the number is
+greater than one, the string will be automatically pluralized.
+
+The reason why we added +@post = Post.new+ in +posts_controller+ is that
+otherwise +@post+ would be +nil+ in our view, and calling
++@post.errors.any?+ would throw an error.
+
+TIP: Rails automatically wraps fields that contain an error with a div
+with class +field_with_errors+. You can define a css rule to make them
+standout.
+
+Now you'll get a nice error message when saving a post without title:
+
+!images/getting_started/form_with_errors.png(Form With Errors)!
h4. Using the Console
diff --git a/guides/source/i18n.textile b/guides/source/i18n.textile
index 320f1e9d20..6179694c40 100644
--- a/guides/source/i18n.textile
+++ b/guides/source/i18n.textile
@@ -866,19 +866,35 @@ The I18n API will catch all of these exceptions when they are thrown in the back
The reason for this is that during development you'd usually want your views to still render even though a translation is missing.
-In other contexts you might want to change this behaviour, though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module:
+In other contexts you might want to change this behaviour, though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module or a class with +#call+ method:
<ruby>
module I18n
- def self.just_raise_that_exception(*args)
- raise args.first
+ class JustRaiseExceptionHandler < ExceptionHandler
+ def call(exception, locale, key, options)
+ if exception.is_a?(MissingTranslation)
+ raise exception.to_exception
+ else
+ super
+ end
+ end
end
end
-I18n.exception_handler = :just_raise_that_exception
+I18n.exception_handler = I18n::JustRaiseExceptionHandler.new
</ruby>
-This would re-raise all caught exceptions including +MissingTranslationData+.
+This would re-raise only the +MissingTranslationData+ exception, passing all other input to the default exception handler.
+
+However, if you are using +I18n::Backend::Pluralization+ this handler will also raise +I18n::MissingTranslationData: translation missing: en.i18n.plural.rule+ exception that should normally be ignored to fall back to the default pluralization rule for English locale. To avoid this you may use additional check for translation key:
+
+<ruby>
+if exception.is_a?(MissingTranslation) && key.to_s != 'i18n.plural.rule'
+ raise exception.to_exception
+else
+ super
+end
+</ruby>
Another example where the default behaviour is less desirable is the Rails TranslationHelper which provides the method +#t+ (as well as +#translate+). When a +MissingTranslationData+ exception occurs in this context, the helper wraps the message into a span with the CSS class +translation_missing+.
diff --git a/guides/source/layouts_and_rendering.textile b/guides/source/layouts_and_rendering.textile
index 7c7fc7044c..c2bba56581 100644
--- a/guides/source/layouts_and_rendering.textile
+++ b/guides/source/layouts_and_rendering.textile
@@ -686,7 +686,7 @@ You can specify a full path relative to the document root, or a URL, if you pref
Rails will then output a +script+ tag such as this:
<html>
-<script src='/assets/main.js' type="text/javascript"></script>
+<script src='/assets/main.js'></script>
</html>
The request to this asset is then served by the Sprockets gem.
@@ -718,8 +718,8 @@ If the application does not use the asset pipeline, the +:defaults+ option loads
Outputting +script+ tags such as this:
<html>
-<script src="/javascripts/jquery.js" type="text/javascript"></script>
-<script src="/javascripts/jquery_ujs.js" type="text/javascript"></script>
+<script src="/javascripts/jquery.js"></script>
+<script src="/javascripts/jquery_ujs.js"></script>
</html>
These two files for jQuery, +jquery.js+ and +jquery_ujs.js+ must be placed inside +public/javascripts+ if the application doesn't use the asset pipeline. These files can be downloaded from the "jquery-rails repository on GitHub":https://github.com/indirect/jquery-rails/tree/master/vendor/assets/javascripts
@@ -805,7 +805,7 @@ To include +http://example.com/main.css+:
<%= stylesheet_link_tag "http://example.com/main.css" %>
</erb>
-By default, the +stylesheet_link_tag+ creates links with +media="screen" rel="stylesheet" type="text/css"+. You can override any of these defaults by specifying an appropriate option (+:media+, +:rel+, or +:type+):
+By default, the +stylesheet_link_tag+ creates links with +media="screen" rel="stylesheet"+. You can override any of these defaults by specifying an appropriate option (+:media+, +:rel+):
<erb>
<%= stylesheet_link_tag "main_print", :media => "print" %>
@@ -1206,7 +1206,7 @@ Suppose you have the following +ApplicationController+ layout:
<head>
<title><%= @page_title or 'Page Title' %></title>
<%= stylesheet_link_tag 'layout' %>
- <style type="text/css"><%= yield :stylesheets %></style>
+ <style><%= yield :stylesheets %></style>
</head>
<body>
<div id="top_menu">Top menu items here</div>
diff --git a/guides/source/migrations.textile b/guides/source/migrations.textile
index 04b453667a..f855072fd8 100644
--- a/guides/source/migrations.textile
+++ b/guides/source/migrations.textile
@@ -51,7 +51,7 @@ end
This migration adds a table called +products+ with a string column called +name+
and a text column called +description+. A primary key column called +id+ will
-also be added, however since this is the default we do not need to ask for this.
+also be added, however since this is the default we do not need to explicitly specify it.
The timestamp columns +created_at+ and +updated_at+ which Active Record
populates automatically will also be added. Reversing this migration is as
simple as dropping the table.
@@ -65,7 +65,7 @@ class AddReceiveNewsletterToUsers < ActiveRecord::Migration
change_table :users do |t|
t.boolean :receive_newsletter, :default => false
end
- User.update_all ["receive_newsletter = ?", true]
+ User.update_all :receive_newsletter => true
end
def down
@@ -82,6 +82,8 @@ it to default to +false+ for new users, but existing users are considered to
have already opted in, so we use the User model to set the flag to +true+ for
existing users.
+h4. Using the change method
+
Rails 3.1 makes migrations smarter by providing a new <tt>change</tt> method.
This method is preferred for writing constructive migrations (adding columns or
tables). The migration knows how to migrate your database and reverse it when
@@ -475,7 +477,16 @@ end
</ruby>
will add an +attachment_id+ column and a string +attachment_type+ column with
-a default value of 'Photo'.
+a default value of 'Photo'. +references+ also allows you to define an
+index directly, instead of using +add_index+ after the +create_table+ call:
+
+<ruby>
+create_table :products do |t|
+ t.references :category, :index => true
+end
+</ruby>
+
+will create an index identical to calling `add_index :products, :category_id`.
NOTE: The +references+ helper does not actually create foreign key constraints
for you. You will need to use +execute+ or a plugin that adds "foreign key
@@ -635,10 +646,9 @@ example,
$ rake db:migrate:up VERSION=20080906120000
</shell>
-will run the +up+ method from the 20080906120000 migration. These tasks still
-check whether the migration has already run, so for example +db:migrate:up
-VERSION=20080906120000+ will do nothing if Active Record believes that
-20080906120000 has already been run.
+will run the +up+ method from the 20080906120000 migration. This task will first
+check whether the migration is already performed and will do nothing if Active Record believes
+that it has already been run.
h4. Changing the output of running migrations
@@ -728,7 +738,7 @@ class AddFlagToProduct < ActiveRecord::Migration
def change
add_column :products, :flag, :boolean
Product.all.each do |product|
- product.update_attributes!(:flag => 'false')
+ product.update_attributes!(:flag => false)
end
end
end
@@ -771,7 +781,7 @@ Both migrations work for Alice.
Bob comes back from vacation and:
-# Updates the source - which contains both migrations and the latests version of
+# Updates the source - which contains both migrations and the latest version of
the Product model.
# Runs outstanding migrations with +rake db:migrate+, which
includes the one that updates the +Product+ model.
diff --git a/guides/source/rails_on_rack.textile b/guides/source/rails_on_rack.textile
index 34dfd3572a..ff862273fd 100644
--- a/guides/source/rails_on_rack.textile
+++ b/guides/source/rails_on_rack.textile
@@ -160,15 +160,10 @@ Append following lines to your application configuration:
<ruby>
# config/application.rb
- config.middleware.delete "Rack::Lock"
- config.middleware.delete "ActionDispatch::Cookies"
- config.middleware.delete "ActionDispatch::Flash"
- config.middleware.delete "ActionDispatch::RemoteIp"
- config.middleware.delete "ActionDispatch::Reloader"
- config.middleware.delete "ActionDispatch::Callbacks"
+config.middleware.delete "Rack::Lock"
</ruby>
-And now inspecting the middleware stack:
+And now if you inspect the middleware stack, you'll find that +Rack::Lock+ will not be part of it.
<shell>
$ rake middleware
@@ -176,19 +171,7 @@ $ rake middleware
use ActionDispatch::Static
use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x00000001c304c8>
use Rack::Runtime
-use Rack::MethodOverride
-use ActionDispatch::RequestId
-use Rails::Rack::Logger
-use ActionDispatch::ShowExceptions
-use ActionDispatch::DebugExceptions
-use ActiveRecord::ConnectionAdapters::ConnectionManagement
-use ActiveRecord::QueryCache
-use ActionDispatch::Session::CookieStore
-use ActionDispatch::ParamsParser
-use ActionDispatch::Head
-use Rack::ConditionalGet
-use Rack::ETag
-use ActionDispatch::BestStandardsSupport
+...
run Myapp::Application.routes
</shell>
diff --git a/guides/source/security.textile b/guides/source/security.textile
index 747a4d6791..c065529cac 100644
--- a/guides/source/security.textile
+++ b/guides/source/security.textile
@@ -385,7 +385,7 @@ params[:user] # => {:name => “ow3ned”, :admin => true}
So if you create a new user using mass-assignment, it may be too easy to become an administrator.
-Note that this vulnerability is not restricted to database columns. Any setter method, unless explicitly protected, is accessible via the <tt>attributes=</tt> method. In fact, this vulnerability is extended even further with the introduction of nested mass assignment (and nested object forms) in Rails 2.3<plus>. The +accepts_nested_attributes_for+ declaration provides us the ability to extend mass assignment to model associations (+has_many+, +has_one+, +has_and_belongs_to_many+). For example:
+Note that this vulnerability is not restricted to database columns. Any setter method, unless explicitly protected, is accessible via the <tt>attributes=</tt> method. In fact, this vulnerability is extended even further with the introduction of nested mass assignment (and nested object forms) in Rails 2.3. The +accepts_nested_attributes_for+ declaration provides us the ability to extend mass assignment to model associations (+has_many+, +has_one+, +has_and_belongs_to_many+). For example:
<ruby>
class Person < ActiveRecord::Base