# Using this method inside a +form_for+ block will set the enclosing form's encoding to <tt>multipart/form-data</tt>.
#
# ==== Options
# * Creates standard HTML attributes for the tag.
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
# * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
# * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
# * <tt>:multiple</tt> - If set to true, *in most updated browsers* the user will be allowed to select multiple files.
# * <tt>:accept</tt> - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.
@@ -849,7 +849,7 @@ NOTE: Certain exceptions are only rescuable from the `ApplicationController` cla
Force HTTPS protocol
--------------------
Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. Since Rails 3.1 you can now use the `force_ssl` method in your controller to enforce that:
Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. You can use the `force_ssl` method in your controller to enforce that:
```ruby
class DinnerController
...
...
@@ -857,7 +857,7 @@ class DinnerController
end
```
Just like the filter, you could also passing `:only` and `:except` to enforce the secure connection only to specific actions:
Just like the filter, you could also pass `:only` and `:except` to enforce the secure connection only to specific actions:
@@ -105,7 +109,7 @@ When you call the `mail` method now, Action Mailer will detect the two templates
#### Wire It Up So That the System Sends the Email When a User Signs Up
There are several ways to do this, some people create Rails Observers to fire off emails, others do it inside of the User Model. However, in Rails 3, mailers are really just another way to render a view. Instead of rendering a view and sending out the HTTP protocol, they are just sending it out through the Email protocols instead. Due to this, it makes sense to just have your controller tell the mailer to send an email when a user is successfully created.
There are several ways to do this, some people create Rails Observers to fire off emails, others do it inside of the User Model. However, mailers are really just another way to render a view. Instead of rendering a view and sending out the HTTP protocol, they are just sending it out through the Email protocols instead. Due to this, it makes sense to just have your controller tell the mailer to send an email when a user is successfully created.
Setting this up is painfully simple.
...
...
@@ -145,10 +149,6 @@ This provides a much simpler implementation that does not require the registerin
The method `welcome_email` returns a `Mail::Message` object which can then just be told `deliver` to send itself out.
NOTE: In previous versions of Rails, you would call `deliver_welcome_email` or `create_welcome_email`. This has been deprecated in Rails 3.0 in favour of just calling the method name itself.
WARNING: Sending out an email should only take a fraction of a second. If you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like Delayed Job.
### Auto encoding header values
Action Mailer now handles the auto encoding of multibyte characters inside of headers and bodies.
@@ -1263,10 +1263,8 @@ Creates a field set for grouping HTML form elements.
Creates a file upload field.
Prior to Rails 3.1, if you are using file uploads, then you will need to set the multipart option for the form tag. Rails 3.1+ does this automatically.
```html+erb
<%= form_tag {action: "post"}, {multipart: true} do %>
<%= form_tag {action: "post"} do %>
<label for="file">File to Upload</label> <%= file_field_tag "file" %>
@@ -1204,7 +1204,7 @@ class Client < ActiveRecord::Base
end
```
### Removing all scoping
### Removing All Scoping
If we wish to remove scoping for any reason we can use the `unscoped` method. This is
especially useful if a `default_scope` is specified in the model and should not be
...
...
@@ -1236,9 +1236,7 @@ You can specify an exclamation point (`!`) on the end of the dynamic finders to
If you want to find both by name and locked, you can chain these finders together by simply typing "`and`" between the fields. For example, `Client.find_by_first_name_and_locked("Ryan", true)`.
WARNING: Up to and including Rails 3.1, when the number of arguments passed to a dynamic finder method is lesser than the number of fields, say `Client.find_by_name_and_locked("Ryan")`, the behavior is to pass `nil` as the missing argument. This is **unintentional** and this behavior will be changed in Rails 3.2 to throw an `ArgumentError`.
Find or build a new object
Find or Build a New Object
--------------------------
It's common that you need to find a record or create it if it doesn't exist. You can do that with the `find_or_create_by` and `find_or_create_by!` methods.
The order in which these classes are returned is unspecified.
WARNING: This method is redefined in some Rails core classes but should be all compatible in Rails 3.1.
NOTE: Defined in `active_support/core_ext/class/subclasses.rb`.
#### `descendants`
...
...
@@ -1157,7 +1160,7 @@ Inserting data into HTML templates needs extra care. For example, you can't just
#### Safe Strings
Active Support has the concept of <i>(html) safe</i> strings since Rails 3. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not.
Active Support has the concept of <i>(html) safe</i> strings. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not.
Strings are considered to be <i>unsafe</i> by default:
...
...
@@ -1194,10 +1197,10 @@ Safe arguments are directly appended:
"".html_safe+"<".html_safe# => "<"
```
These methods should not be used in ordinary views. In Rails 3 unsafe values are automatically escaped:
These methods should not be used in ordinary views. Unsafe values are automatically escaped:
```erb
<%=@review.title%><%# fine in Rails 3, escaped if needed %>
<%=@review.title%><%# fine, escaped if needed %>
```
To insert something verbatim use the `raw` helper rather than calling `html_safe`:
The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB.
Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets. Rails 3.1 is integrated with Sprockets through Action Pack which depends on the `sprockets` gem, by default.
Making the asset pipeline a core feature of Rails means that all developers can benefit from the power of having their assets pre-processed, compressed and minified by one central library, Sprockets. This is part of Rails' "fast by default" strategy as outlined by DHH in his keynote at RailsConf 2011.
In Rails 3.1, the asset pipeline is enabled by default. It can be disabled in `config/application.rb` by putting this line inside the application class definition:
The asset pipeline is enabled by default. It can be disabled in `config/application.rb` by putting this line inside the application class definition:
```ruby
config.assets.enabled=false
...
...
@@ -100,7 +98,24 @@ In production, Rails precompiles these files to `public/assets` by default. The
When you generate a scaffold or a controller, Rails also generates a JavaScript file (or CoffeeScript file if the `coffee-rails` gem is in the `Gemfile`) and a Cascading Style Sheet file (or SCSS file if `sass-rails` is in the `Gemfile`) for that controller.
For example, if you generate a `ProjectsController`, Rails will also add a new file at `app/assets/javascripts/projects.js.coffee` and another at `app/assets/stylesheets/projects.css.scss`. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as `<%= javascript_include_tag params[:controller] %>` or `<%= stylesheet_link_tag params[:controller] %>`.
For example, if you generate a `ProjectsController`, Rails will also add a new file at `app/assets/javascripts/projects.js.coffee` and another at `app/assets/stylesheets/projects.css.scss`. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as `<%= javascript_include_tag params[:controller] %>` or `<%= stylesheet_link_tag params[:controller] %>`. Note that you have to set `config.assets.precompile` in `config/environments/production.rb` if you want to precomepile them and use in production mode. You can append them one by one or do something like this:
NOTE: You must have an [ExecJS](https://github.com/sstephenson/execjs#readme) supported runtime in order to use CoffeeScript. If you are using Mac OS X or Windows you have a JavaScript runtime installed in your operating system. Check [ExecJS](https://github.com/sstephenson/execjs#readme) documentation to know all supported JavaScript runtimes.
...
...
@@ -114,7 +129,7 @@ Pipeline assets can be placed inside an application in one of three locations: `
*`vendor/assets` is for assets that are owned by outside entities, such as code for JavaScript plugins and CSS frameworks.
#### Search paths
#### Search Paths
When a file is referenced from a manifest or a helper, Sprockets searches the three default asset locations for it.
...
...
@@ -162,7 +177,7 @@ Paths are traversed in the order that they occur in the search path. By default,
It is important to note that files you want to reference outside a manifest must be added to the precompile array or they will not be available in the production environment.
#### Using index files
#### Using Index Files
Sprockets uses files named `index` (with the relevant extensions) for a special purpose.
...
...
@@ -270,8 +285,6 @@ For example, a new Rails application includes a default `app/assets/javascripts/
In JavaScript files, the directives begin with `//=`. In this case, the file is using the `require` and the `require_tree` directives. The `require` directive is used to tell Sprockets the files that you wish to require. Here, you are requiring the files `jquery.js` and `jquery_ujs.js` that are available somewhere in the search path for Sprockets. You need not supply the extensions explicitly. Sprockets assumes you are requiring a `.js` file when done from within a `.js` file.
NOTE. In Rails 3.1 the `jquery-rails` gem provides the `jquery.js` and `jquery_ujs.js` files via the asset pipeline. You won't see them in the application tree.
The `require_tree` directive tells Sprockets to recursively include _all_ JavaScript files in the specified directory into the output. These paths must be specified relative to the manifest file. You can also use the `require_directory` directive which includes all JavaScript files only in the directory specified, without recursion.
Directives are processed top to bottom, but the order in which files are included by `require_tree` is unspecified. You should not rely on any particular order among those. If you need to ensure some particular JavaScript ends up above some other in the concatenated file, require the prerequisite file first in the manifest. Note that the family of `require` directives prevents files from being included twice in the output.
...
...
@@ -337,7 +350,7 @@ would generate this HTML:
The `body` param is required by Sprockets.
### Turning Debugging off
### Turning Debugging Off
You can turn off debug mode by updating `config/environments/development.rb` to include:
...
...
@@ -462,7 +475,7 @@ The default location for the manifest is the root of the location specified in `
NOTE: If there are missing precompiled files in production you will get an `Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError` exception indicating the name of the missing file(s).
#### Far-future Expires header
#### Far-future Expires Header
Precompiled assets exist on the filesystem and are served directly by your web server. They do not have far-future headers by default, so to get the benefit of fingerprinting you'll have to update your server configuration to add them.
...
...
@@ -492,7 +505,7 @@ location ~ ^/assets/ {
}
```
#### GZip compression
#### GZip Compression
When files are precompiled, Sprockets also creates a [gzipped](http://en.wikipedia.org/wiki/Gzip) (.gz) version of your assets. Web servers are typically configured to use a moderate compression ratio as a compromise, but since precompilation happens once, Sprockets uses the maximum compression ratio, thus reducing the size of the data transfer to the minimum. On the other hand, web servers can be configured to serve compressed content directly from disk, rather than deflating non-compressed files themselves.
...
...
@@ -648,7 +661,7 @@ This can be changed to something else:
config.assets.prefix = "/some_other_path"
```
This is a handy option if you are updating an existing project (pre Rails 3.1) that already uses this path or you wish to use this path for a new resource.
This is a handy option if you are updating an older project that didn't use the asset pipeline and that already uses this path or you wish to use this path for a new resource.
@@ -452,7 +452,7 @@ class CreateAssemblyPartJoinTable < ActiveRecord::Migration
end
```
We pass `id: false` to `create_table` because that table does not represent a model. That's required for the association to work properly. If you observe any strange behavior in a `has_and_belongs_to_many` association like mangled models IDs, or exceptions about conflicting IDs chances are you forgot that bit.
We pass `id: false` to `create_table` because that table does not represent a model. That's required for the association to work properly. If you observe any strange behavior in a `has_and_belongs_to_many` association like mangled models IDs, or exceptions about conflicting IDs, chances are you forgot that bit.
@@ -135,8 +135,6 @@ These configuration methods are to be called on a `Rails::Railtie` object, such
### Configuring Assets
Rails 3.1 and up, by default, is set up to use the `sprockets` gem to manage assets within an application. This gem concatenates and compresses assets in order to make serving them much less painful.
*`config.assets.enabled` a flag that controls whether the asset pipeline is enabled. It is explicitly initialized in `config/application.rb`.
*`config.assets.compress` a flag that enables the compression of compiled assets. It is explicitly set to true in `config/production.rb`.
...
...
@@ -165,7 +163,7 @@ Rails 3.1 and up, by default, is set up to use the `sprockets` gem to manage ass
### Configuring Generators
Rails 3 allows you to alter what generators are used with the `config.generators` method. This method takes a block:
Rails allows you to alter what generators are used with the `config.generators` method. This method takes a block:
@@ -5,11 +5,11 @@ This guide covers ways in which _you_ can become a part of the ongoing developme
After reading this guide, you will know:
*Using GitHub to report issues.
*Cloning master and running the test suite.
* Helping to resolve existing issues.
*Contributing to the Ruby on Rails documentation.
*Contributing to the Ruby on Rails code.
*How to use GitHub to report issues.
*How to clone master and run the test suite.
* How to help resolve existing issues.
*How to contribute to the Ruby on Rails documentation.
*How to contribute to the Ruby on Rails code.
Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation — all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.
...
...
@@ -91,7 +91,7 @@ You can invoke `test_jdbcmysql`, `test_jdbcsqlite3` or `test_jdbcpostgresql` als
The test suite runs with warnings enabled. Ideally, Ruby on Rails should issue no warnings, but there may be a few, as well as some from third-party libraries. Please ignore (or fix!) them, if any, and submit patches that do not issue new warnings.
As of this writing (December, 2010) they are specially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag:
As of this writing (December, 2010) they are especially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag:
```bash
$ RUBYOPT=-W0 bundle exec rake test
...
...
@@ -205,7 +205,7 @@ TIP: Changes that are cosmetic in nature and do not add anything substantial to
### Follow the Coding Conventions
Rails follows a simple set of coding style conventions.
Rails follows a simple set of coding style conventions:
* Two spaces, no tabs (for indentation).
* No trailing whitespace. Blank lines should not have any spaces.
@@ -35,7 +35,7 @@ Finally, engines would not have been possible without the work of James Adam, Pi
Generating an engine
--------------------
To generate an engine with Rails 3.2, you will need to run the plugin generator and pass it options as appropriate to the need. For the "blorgh" example, you will need to create a "mountable" engine, running this command in a terminal:
To generate an engine, you will need to run the plugin generator and pass it options as appropriate to the need. For the "blorgh" example, you will need to create a "mountable" engine, running this command in a terminal:
@@ -594,8 +594,6 @@ The following two forms both upload a file.
<%end%>
```
NOTE: Since Rails 3.1, forms rendered using `form_for` have their encoding set to `multipart/form-data` automatically once a `file_field` is used inside the block. Previous versions required you to set this explicitly.
Rails provides the usual pair of helpers: the barebones `file_field_tag` and the model oriented `file_field`. The only difference with other helpers is that you cannot set a default value for file inputs as this would have no meaning. As you would expect in the first case the uploaded file is in `params[:picture]` and in the second case in `params[:person][:picture]`.
@@ -5,7 +5,7 @@ This guide covers getting up and running with Ruby on Rails.
After reading this guide, you will know:
*Installing Rails, creating a new Rails application, and connecting your
*How to install Rails, create a new Rails application, and connect your
application to a database.
* The general layout of a Rails application.
* The basic principles of MVC (Model, View, Controller) and RESTful design.
...
...
@@ -77,7 +77,7 @@ TIP: The examples below use # and $ to denote superuser and regular user termina
Open up a command line prompt. On Mac OS X open Terminal.app, on Windows choose
"Run" from your Start menu and type 'cmd.exe'. Any commands prefaced with a
dollar sign `$` should be run in the command line. Verify sure you have a
dollar sign `$` should be run in the command line. Verify that you have a
current version of Ruby installed:
```bash
...
...
@@ -101,11 +101,11 @@ To verify that you have everything installed correctly, you should be able to ru
$ rails --version
```
If it says something like "Rails 3.2.9" you are ready to continue.
If it says something like "Rails 3.2.9", you are ready to continue.
### Creating the Blog Application
Rails comes with a number of generators that are designed to make your development life easier. One of these is the new application generator, which will provide you with the foundation of a Rails application so that you don't have to write it yourself.
Rails comes with a number of scripts called generators that are designed to make your development life easier by creating everything that's necessary to start working on a particular task. One of these is the new application generator, which will provide you with the foundation of a fresh Rails application so that you don't have to write it yourself.
To use this generator, open a terminal, navigate to a directory where you have rights to create files, and type:
To be explicit, you can use `render` with the `:action` option (though this is no longer necessary in Rails 3.0):
```ruby
defupdate
@book=Book.find(params[:id])
if@book.update_attributes(params[:book])
redirect_to(@book)
else
renderaction: "edit"
end
end
```
WARNING: Using `render` with `:action` is a frequent source of confusion for Rails newcomers. The specified action is used to determine which view to render, but Rails does _not_ run any of the code for that action in the controller. Any instance variables that you require in the view must be set up in the current action before calling `render`.
#### Rendering an Action's Template from Another Controller
What if you want to render a template from an entirely different controller from the one that contains the action code? You can also do that with `render`, which accepts the full path (relative to `app/views`) of the template to render. For example, if you're running code in an `AdminProductsController` that lives in `app/controllers/admin`, you can render the results of an action to a template in `app/views/products` this way:
...
...
@@ -674,7 +659,7 @@ There are three tag options available for the `auto_discovery_link_tag`:
The `javascript_include_tag` helper returns an HTML `script` tag for each source provided.
If you are using Rails with the [Asset Pipeline](asset_pipeline.html) enabled, this helper will generate a link to `/assets/javascripts/` rather than `public/javascripts` which was used in earlier versions of Rails. This link is then served by the Sprockets gem, which was introduced in Rails 3.1.
If you are using Rails with the [Asset Pipeline](asset_pipeline.html) enabled, this helper will generate a link to `/assets/javascripts/` rather than `public/javascripts` which was used in earlier versions of Rails. This link is then served by the asset pipeline.
A JavaScript file within a Rails application or Rails engine goes in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`. These locations are explained in detail in the [Asset Organization section in the Asset Pipeline Guide](asset_pipeline.html#asset-organization)
...
...
@@ -843,7 +828,7 @@ You can even use dynamic paths such as `cache/#{current_site}/main/display`.
The `image_tag` helper builds an HTML `<img />` tag to the specified file. By default, files are loaded from `public/images`.
WARNING: Note that you must specify the extension of the image. Previous versions of Rails would allow you to just use the image name and would append `.png` if no extension was given but Rails 3.0 does not.
WARNING: Note that you must specify the extension of the image.
```erb
<%=image_tag"header.png"%>
...
...
@@ -1091,8 +1076,6 @@ Every partial also has a local variable with the same name as the partial (minus
Within the `customer` partial, the `customer` variable will refer to `@new_customer` from the parent view.
WARNING: In previous versions of Rails, the default local variable would look for an instance variable with the same name as the partial in the parent. This behavior was deprecated in 2.3 and has been removed in Rails 3.0.
If you have an instance of a model to render into a partial, you can use a shorthand syntax:
```erb
...
...
@@ -1120,7 +1103,7 @@ Partials are very useful in rendering collections. When you pass a collection to
When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is `_product`, and within the `_product` partial, you can refer to `product` to get the instance that is being rendered.
In Rails 3.0, there is also a shorthand for this. Assuming `@products` is a collection of `product` instances, you can simply write this in the `index.html.erb` to produce the same result:
There is also a shorthand for this. Assuming `@products` is a collection of `product` instances, you can simply write this in the `index.html.erb` to produce the same result:
@@ -733,12 +733,6 @@ get '*a/foo/*b', to: 'test#index'
would match `zoo/woo/foo/bar/baz` with `params[:a]` equals `'zoo/woo'`, and `params[:b]` equals `'bar/baz'`.
NOTE: Starting from Rails 3.1, wildcard segments will always match the optional format segment by default. For example if you have this route:
```ruby
get'*pages',to: 'pages#show'
```
NOTE: By requesting `'/foo/bar.json'`, your `params[:pages]` will be equals to `'foo/bar'` with the request format of JSON. If you want the old 3.0.x behavior back, you could supply `format: false` like this: