mirror of https://github.com/rails/rails
Convert inline code tags to Markdown
This commit is contained in:
parent
872b7af337
commit
c89c163a0e
|
@ -110,7 +110,7 @@ To send a hash you include the key name inside the brackets:
|
|||
</form>
|
||||
```
|
||||
|
||||
When this form is submitted, the value of +params[:client]+ will be <tt>{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}</tt>. Note the nested hash in +params[:client][:address]+.
|
||||
When this form is submitted, the value of +params[:client]+ will be `{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}`. Note the nested hash in +params[:client][:address]+.
|
||||
|
||||
Note that the +params+ hash is actually an instance of +HashWithIndifferentAccess+ from Active Support, which acts like a hash that lets you use symbols and strings interchangeably as keys.
|
||||
|
||||
|
@ -124,7 +124,7 @@ So for example, if you are sending this JSON parameter:
|
|||
{ "company": { "name": "acme", "address": "123 Carrot Street" } }
|
||||
```
|
||||
|
||||
You'll get <tt>params[:company]</tt> as <tt>{ :name => "acme", "address" => "123 Carrot Street" }</tt>.
|
||||
You'll get `params[:company]` as `{ :name => "acme", "address" => "123 Carrot Street" }`.
|
||||
|
||||
Also, if you've turned on +config.wrap_parameters+ in your initializer or calling +wrap_parameters+ in your controller, you can safely omit the root element in the JSON/XML parameter. The parameters will be cloned and wrapped in the key according to your controller's name by default. So the above parameter can be written as:
|
||||
|
||||
|
@ -423,7 +423,7 @@ class UsersController < ApplicationController
|
|||
end
|
||||
```
|
||||
|
||||
Notice that in the above case code is <tt>render :xml => @users</tt> and not <tt>render :xml => @users.to_xml</tt>. That is because if the input is not string then rails automatically invokes +to_xml+ .
|
||||
Notice that in the above case code is `render :xml => @users` and not `render :xml => @users.to_xml`. That is because if the input is not string then rails automatically invokes +to_xml+ .
|
||||
|
||||
|
||||
Filters
|
||||
|
@ -712,7 +712,7 @@ end
|
|||
|
||||
This will read and stream the file 4kB at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the +:stream+ option or adjust the block size with the +:buffer_size+ option.
|
||||
|
||||
If +:type+ is not specified, it will be guessed from the file extension specified in +:filename+. If the content type is not registered for the extension, <tt>application/octet-stream</tt> will be used.
|
||||
If +:type+ is not specified, it will be guessed from the file extension specified in +:filename+. If the content type is not registered for the extension, `application/octet-stream` will be used.
|
||||
|
||||
WARNING: Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
|
||||
|
||||
|
@ -753,7 +753,7 @@ GET /clients/1.pdf
|
|||
Parameter Filtering
|
||||
-------------------
|
||||
|
||||
Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. You can filter certain request parameters from your log files by appending them to <tt>config.filter_parameters</tt> in the application configuration. These parameters will be marked [FILTERED] in the log.
|
||||
Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. You can filter certain request parameters from your log files by appending them to `config.filter_parameters` in the application configuration. These parameters will be marked [FILTERED] in the log.
|
||||
|
||||
```ruby
|
||||
config.filter_parameters << :password
|
||||
|
|
|
@ -10,7 +10,7 @@ WARNING. This guide is based on Rails 3.2. Some of the code shown here will not
|
|||
Introduction
|
||||
------------
|
||||
|
||||
Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from +ActionMailer::Base+ and live in +app/mailers+. Those mailers have associated views that appear alongside controller views in +app/views+.
|
||||
Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from `ActionMailer::Base` and live in `app/mailers`. Those mailers have associated views that appear alongside controller views in `app/views`.
|
||||
|
||||
Sending Emails
|
||||
--------------
|
||||
|
@ -34,7 +34,7 @@ So we got the mailer, the views, and the tests.
|
|||
|
||||
#### Edit the Mailer
|
||||
|
||||
+app/mailers/user_mailer.rb+ contains an empty mailer:
|
||||
`app/mailers/user_mailer.rb` contains an empty mailer:
|
||||
|
||||
```ruby
|
||||
class UserMailer < ActionMailer::Base
|
||||
|
@ -42,7 +42,7 @@ class UserMailer < ActionMailer::Base
|
|||
end
|
||||
```
|
||||
|
||||
Let's add a method called +welcome_email+, that will send an email to the user's registered email address:
|
||||
Let's add a method called `welcome_email`, that will send an email to the user's registered email address:
|
||||
|
||||
```ruby
|
||||
class UserMailer < ActionMailer::Base
|
||||
|
@ -58,14 +58,14 @@ end
|
|||
|
||||
Here is a quick explanation of the items presented in the preceding method. For a full list of all available options, please have a look further down at the Complete List of Action Mailer user-settable attributes section.
|
||||
|
||||
* <tt>default Hash</tt> - This is a hash of default values for any email you send, in this case we are setting the <tt>:from</tt> header to a value for all messages in this class, this can be overridden on a per email basis
|
||||
* +mail+ - The actual email message, we are passing the <tt>:to</tt> and <tt>:subject</tt> headers in.
|
||||
* `default Hash` - This is a hash of default values for any email you send, in this case we are setting the `:from` header to a value for all messages in this class, this can be overridden on a per email basis
|
||||
* `mail` - The actual email message, we are passing the `:to` and `:subject` headers in.
|
||||
|
||||
Just like controllers, any instance variables we define in the method become available for use in the views.
|
||||
|
||||
#### Create a Mailer View
|
||||
|
||||
Create a file called +welcome_email.html.erb+ in +app/views/user_mailer/+. This will be the template used for the email, formatted in HTML:
|
||||
Create a file called `welcome_email.html.erb` in `app/views/user_mailer/`. This will be the template used for the email, formatted in HTML:
|
||||
|
||||
```erb
|
||||
<!DOCTYPE html>
|
||||
|
@ -87,7 +87,7 @@ Create a file called +welcome_email.html.erb+ in +app/views/user_mailer/+. This
|
|||
</html>
|
||||
```
|
||||
|
||||
It is also a good idea to make a text part for this email. To do this, create a file called +welcome_email.text.erb+ in +app/views/user_mailer/+:
|
||||
It is also a good idea to make a text part for this email. To do this, create a file called `welcome_email.text.erb` in `app/views/user_mailer/`:
|
||||
|
||||
```erb
|
||||
Welcome to example.com, <%= @user.name %>
|
||||
|
@ -101,7 +101,7 @@ To login to the site, just follow this link: <%= @url %>.
|
|||
Thanks for joining and have a great day!
|
||||
```
|
||||
|
||||
When you call the +mail+ method now, Action Mailer will detect the two templates (text and HTML) and automatically generate a <tt>multipart/alternative</tt> email.
|
||||
When you call the `mail` method now, Action Mailer will detect the two templates (text and HTML) and automatically generate a `multipart/alternative` email.
|
||||
|
||||
#### Wire It Up So That the System Sends the Email When a User Signs Up
|
||||
|
||||
|
@ -109,14 +109,14 @@ There are several ways to do this, some people create Rails Observers to fire of
|
|||
|
||||
Setting this up is painfully simple.
|
||||
|
||||
First off, we need to create a simple +User+ scaffold:
|
||||
First off, we need to create a simple `User` scaffold:
|
||||
|
||||
```shell
|
||||
$ rails generate scaffold user name:string email:string login:string
|
||||
$ rake db:migrate
|
||||
```
|
||||
|
||||
Now that we have a user model to play with, we will just edit the +app/controllers/users_controller.rb+ make it instruct the UserMailer to deliver an email to the newly created user by editing the create action and inserting a call to <tt>UserMailer.welcome_email</tt> right after the user is successfully saved:
|
||||
Now that we have a user model to play with, we will just edit the `app/controllers/users_controller.rb` make it instruct the UserMailer to deliver an email to the newly created user by editing the create action and inserting a call to `UserMailer.welcome_email` right after the user is successfully saved:
|
||||
|
||||
```ruby
|
||||
class UsersController < ApplicationController
|
||||
|
@ -143,9 +143,9 @@ end
|
|||
|
||||
This provides a much simpler implementation that does not require the registering of observers and the like.
|
||||
|
||||
The method +welcome_email+ returns a <tt>Mail::Message</tt> object which can then just be told +deliver+ to send itself out.
|
||||
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.
|
||||
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.
|
||||
|
||||
|
@ -161,33 +161,33 @@ For more complex examples such as defining alternate character sets or self-enco
|
|||
|
||||
There are just three methods that you need to send pretty much any email message:
|
||||
|
||||
* <tt>headers</tt> - Specifies any header on the email you want. You can pass a hash of header field names and value pairs, or you can call <tt>headers[:field_name] = 'value'</tt>.
|
||||
* <tt>attachments</tt> - Allows you to add attachments to your email. For example, <tt>attachments['file-name.jpg'] = File.read('file-name.jpg')</tt>.
|
||||
* <tt>mail</tt> - Sends the actual email itself. You can pass in headers as a hash to the mail method as a parameter, mail will then create an email, either plain text, or multipart, depending on what email templates you have defined.
|
||||
* `headers` - Specifies any header on the email you want. You can pass a hash of header field names and value pairs, or you can call `headers[:field_name] = 'value'`.
|
||||
* `attachments` - Allows you to add attachments to your email. For example, `attachments['file-name.jpg'] = File.read('file-name.jpg')`.
|
||||
* `mail` - Sends the actual email itself. You can pass in headers as a hash to the mail method as a parameter, mail will then create an email, either plain text, or multipart, depending on what email templates you have defined.
|
||||
|
||||
#### Custom Headers
|
||||
|
||||
Defining custom headers are simple, you can do it one of three ways:
|
||||
|
||||
* Defining a header field as a parameter to the +mail+ method:
|
||||
* Defining a header field as a parameter to the `mail` method:
|
||||
|
||||
```ruby
|
||||
mail("X-Spam" => value)
|
||||
```
|
||||
|
||||
* Passing in a key value assignment to the +headers+ method:
|
||||
* Passing in a key value assignment to the `headers` method:
|
||||
|
||||
```ruby
|
||||
headers["X-Spam"] = value
|
||||
```
|
||||
|
||||
* Passing a hash of key value pairs to the +headers+ method:
|
||||
* Passing a hash of key value pairs to the `headers` method:
|
||||
|
||||
```ruby
|
||||
headers {"X-Spam" => value, "X-Special" => another_value}
|
||||
```
|
||||
|
||||
TIP: All <tt>X-Value</tt> headers per the RFC2822 can appear more than once. If you want to delete an <tt>X-Value</tt> header, you need to assign it a value of <tt>nil</tt>.
|
||||
TIP: All `X-Value` headers per the RFC2822 can appear more than once. If you want to delete an `X-Value` header, you need to assign it a value of `nil`.
|
||||
|
||||
#### Adding Attachments
|
||||
|
||||
|
@ -199,7 +199,7 @@ Adding attachments has been simplified in Action Mailer 3.0.
|
|||
attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
|
||||
```
|
||||
|
||||
NOTE: Mail will automatically Base64 encode an attachment. If you want something different, pre-encode your content and pass in the encoded content and encoding in a +Hash+ to the +attachments+ method.
|
||||
NOTE: Mail will automatically Base64 encode an attachment. If you want something different, pre-encode your content and pass in the encoded content and encoding in a `Hash` to the `attachments` method.
|
||||
|
||||
* Pass the file name and specify headers and content and Action Mailer and Mail will use the settings you pass in.
|
||||
|
||||
|
@ -216,7 +216,7 @@ NOTE: If you specify an encoding, Mail will assume that your content is already
|
|||
|
||||
Action Mailer 3.0 makes inline attachments, which involved a lot of hacking in pre 3.0 versions, much simpler and trivial as they should be.
|
||||
|
||||
* Firstly, to tell Mail to turn an attachment into an inline attachment, you just call <tt>#inline</tt> on the attachments method within your Mailer:
|
||||
* Firstly, to tell Mail to turn an attachment into an inline attachment, you just call `#inline` on the attachments method within your Mailer:
|
||||
|
||||
```ruby
|
||||
def welcome
|
||||
|
@ -224,7 +224,7 @@ def welcome
|
|||
end
|
||||
```
|
||||
|
||||
* Then in your view, you can just reference <tt>attachments[]</tt> as a hash and specify which attachment you want to show, calling +url+ on it and then passing the result into the <tt>image_tag</tt> method:
|
||||
* Then in your view, you can just reference `attachments[]` as a hash and specify which attachment you want to show, calling `url` on it and then passing the result into the `image_tag` method:
|
||||
|
||||
```erb
|
||||
<p>Hello there, this is our image</p>
|
||||
|
@ -232,7 +232,7 @@ end
|
|||
<%= image_tag attachments['image.jpg'].url %>
|
||||
```
|
||||
|
||||
* As this is a standard call to +image_tag+ you can pass in an options hash after the attachment URL as you could for any other image:
|
||||
* As this is a standard call to `image_tag` you can pass in an options hash after the attachment URL as you could for any other image:
|
||||
|
||||
```erb
|
||||
<p>Hello there, this is our image</p>
|
||||
|
@ -243,7 +243,7 @@ end
|
|||
|
||||
#### Sending Email To Multiple Recipients
|
||||
|
||||
It is possible to send email to one or more recipients in one email (e.g., informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The list of emails can be an array of email addresses or a single string with the addresses separated by commas.
|
||||
It is possible to send email to one or more recipients in one email (e.g., informing all admins of a new signup) by setting the list of emails to the `:to` key. The list of emails can be an array of email addresses or a single string with the addresses separated by commas.
|
||||
|
||||
```ruby
|
||||
class AdminMailer < ActionMailer::Base
|
||||
|
@ -257,12 +257,12 @@ class AdminMailer < ActionMailer::Base
|
|||
end
|
||||
```
|
||||
|
||||
The same format can be used to set carbon copy (Cc:) and blind carbon copy (Bcc:) recipients, by using the <tt>:cc</tt> and <tt>:bcc</tt> keys respectively.
|
||||
The same format can be used to set carbon copy (Cc:) and blind carbon copy (Bcc:) recipients, by using the `:cc` and `:bcc` keys respectively.
|
||||
|
||||
#### Sending Email With Name
|
||||
|
||||
Sometimes you wish to show the name of the person instead of just their email address when they receive the email. The trick to doing that is
|
||||
to format the email address in the format <tt>"Name <email>"</tt>.
|
||||
to format the email address in the format `"Name <email>"`.
|
||||
|
||||
```ruby
|
||||
def welcome_email(user)
|
||||
|
@ -274,7 +274,7 @@ end
|
|||
|
||||
### Mailer Views
|
||||
|
||||
Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because its name is the same as the mailer method. In our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.html.erb+ for the HTML version and +welcome_email.text.erb+ for the plain text version.
|
||||
Mailer views are located in the `app/views/name_of_mailer_class` directory. The specific mailer view is known to the class because its name is the same as the mailer method. In our example from above, our mailer view for the `welcome_email` method will be in `app/views/user_mailer/welcome_email.html.erb` for the HTML version and `welcome_email.text.erb` for the plain text version.
|
||||
|
||||
To change the default mailer view for your action you do something like:
|
||||
|
||||
|
@ -293,7 +293,7 @@ class UserMailer < ActionMailer::Base
|
|||
end
|
||||
```
|
||||
|
||||
In this case it will look for templates at +app/views/notifications+ with name +another+.
|
||||
In this case it will look for templates at `app/views/notifications` with name `another`.
|
||||
|
||||
If you want more flexibility you can also pass a block and render specific templates or even render inline or text without using a template file:
|
||||
|
||||
|
@ -314,11 +314,11 @@ class UserMailer < ActionMailer::Base
|
|||
end
|
||||
```
|
||||
|
||||
This will render the template 'another_template.html.erb' for the HTML part and use the rendered text for the text part. The render command is the same one used inside of Action Controller, so you can use all the same options, such as <tt>:text</tt>, <tt>:inline</tt> etc.
|
||||
This will render the template 'another_template.html.erb' for the HTML part and use the rendered text for the text part. The render command is the same one used inside of Action Controller, so you can use all the same options, such as `:text`, `:inline` etc.
|
||||
|
||||
### Action Mailer Layouts
|
||||
|
||||
Just like controller views, you can also have mailer layouts. The layout name needs to be the same as your mailer, such as +user_mailer.html.erb+ and +user_mailer.text.erb+ to be automatically recognized by your mailer as a layout.
|
||||
Just like controller views, you can also have mailer layouts. The layout name needs to be the same as your mailer, such as `user_mailer.html.erb` and `user_mailer.text.erb` to be automatically recognized by your mailer as a layout.
|
||||
|
||||
In order to use a different file just use:
|
||||
|
||||
|
@ -328,9 +328,9 @@ class UserMailer < ActionMailer::Base
|
|||
end
|
||||
```
|
||||
|
||||
Just like with controller views, use +yield+ to render the view inside the layout.
|
||||
Just like with controller views, use `yield` to render the view inside the layout.
|
||||
|
||||
You can also pass in a <tt>:layout => 'layout_name'</tt> option to the render call inside the format block to specify different layouts for different actions:
|
||||
You can also pass in a `:layout => 'layout_name'` option to the render call inside the format block to specify different layouts for different actions:
|
||||
|
||||
```ruby
|
||||
class UserMailer < ActionMailer::Base
|
||||
|
@ -343,13 +343,13 @@ class UserMailer < ActionMailer::Base
|
|||
end
|
||||
```
|
||||
|
||||
Will render the HTML part using the <tt>my_layout.html.erb</tt> file and the text part with the usual <tt>user_mailer.text.erb</tt> file if it exists.
|
||||
Will render the HTML part using the `my_layout.html.erb` file and the text part with the usual `user_mailer.text.erb` file if it exists.
|
||||
|
||||
### Generating URLs in Action Mailer Views
|
||||
|
||||
URLs can be generated in mailer views using +url_for+ or named routes.
|
||||
URLs can be generated in mailer views using `url_for` or named routes.
|
||||
|
||||
Unlike controllers, the mailer instance doesn't have any context about the incoming request so you'll need to provide the +:host+, +:controller+, and +:action+:
|
||||
Unlike controllers, the mailer instance doesn't have any context about the incoming request so you'll need to provide the `:host`, `:controller`, and `:action`:
|
||||
|
||||
```erb
|
||||
<%= url_for(:host => "example.com",
|
||||
|
@ -357,7 +357,7 @@ Unlike controllers, the mailer instance doesn't have any context about the incom
|
|||
:action => "greeting") %>
|
||||
```
|
||||
|
||||
When using named routes you only need to supply the +:host+:
|
||||
When using named routes you only need to supply the `:host`:
|
||||
|
||||
```erb
|
||||
<%= user_url(@user, :host => "example.com") %>
|
||||
|
@ -365,19 +365,19 @@ When using named routes you only need to supply the +:host+:
|
|||
|
||||
Email clients have no web context and so paths have no base URL to form complete web addresses. Thus, when using named routes only the "_url" variant makes sense.
|
||||
|
||||
It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt> option as a configuration option in <tt>config/application.rb</tt>:
|
||||
It is also possible to set a default host that will be used in all mailers by setting the `:host` option as a configuration option in `config/application.rb`:
|
||||
|
||||
```ruby
|
||||
config.action_mailer.default_url_options = { :host => "example.com" }
|
||||
```
|
||||
|
||||
If you use this setting, you should pass the <tt>:only_path => false</tt> option when using +url_for+. This will ensure that absolute URLs are generated because the +url_for+ view helper will, by default, generate relative URLs when a <tt>:host</tt> option isn't explicitly provided.
|
||||
If you use this setting, you should pass the `:only_path => false` option when using `url_for`. This will ensure that absolute URLs are generated because the `url_for` view helper will, by default, generate relative URLs when a `:host` option isn't explicitly provided.
|
||||
|
||||
### Sending Multipart Emails
|
||||
|
||||
Action Mailer will automatically send multipart emails if you have different templates for the same action. So, for our UserMailer example, if you have +welcome_email.text.erb+ and +welcome_email.html.erb+ in +app/views/user_mailer+, Action Mailer will automatically send a multipart email with the HTML and text versions setup as different parts.
|
||||
Action Mailer will automatically send multipart emails if you have different templates for the same action. So, for our UserMailer example, if you have `welcome_email.text.erb` and `welcome_email.html.erb` in `app/views/user_mailer`, Action Mailer will automatically send a multipart email with the HTML and text versions setup as different parts.
|
||||
|
||||
The order of the parts getting inserted is determined by the <tt>:parts_order</tt> inside of the <tt>ActionMailer::Base.default</tt> method. If you want to explicitly alter the order, you can either change the <tt>:parts_order</tt> or explicitly render the parts in a different order:
|
||||
The order of the parts getting inserted is determined by the `:parts_order` inside of the `ActionMailer::Base.default` method. If you want to explicitly alter the order, you can either change the `:parts_order` or explicitly render the parts in a different order:
|
||||
|
||||
```ruby
|
||||
class UserMailer < ActionMailer::Base
|
||||
|
@ -397,7 +397,7 @@ Will put the HTML part first, and the plain text part second.
|
|||
|
||||
### Sending Emails with Attachments
|
||||
|
||||
Attachments can be added by using the +attachments+ method:
|
||||
Attachments can be added by using the `attachments` method:
|
||||
|
||||
```ruby
|
||||
class UserMailer < ActionMailer::Base
|
||||
|
@ -411,14 +411,13 @@ class UserMailer < ActionMailer::Base
|
|||
end
|
||||
```
|
||||
|
||||
The above will send a multipart email with an attachment, properly nested with the top level being <tt>multipart/mixed</tt> and the first part being a <tt>multipart/alternative</tt> containing the plain text and HTML email messages.
|
||||
The above will send a multipart email with an attachment, properly nested with the top level being `multipart/mixed` and the first part being a `multipart/alternative` containing the plain text and HTML email messages.
|
||||
|
||||
<<<<<<< HEAD
|
||||
h5. Sending Emails with Dynamic Delivery Options
|
||||
#### Sending Emails with Dynamic Delivery Options
|
||||
|
||||
If you wish to override the default delivery options (e.g. SMTP credentials) while delivering emails, you can do this using +delivery_method_options+ in the mailer action.
|
||||
If you wish to override the default delivery options (e.g. SMTP credentials) while delivering emails, you can do this using `delivery_method_options` in the mailer action.
|
||||
|
||||
<ruby>
|
||||
```ruby
|
||||
class UserMailer < ActionMailer::Base
|
||||
def welcome_email(user,company)
|
||||
@user = user
|
||||
|
@ -427,21 +426,18 @@ class UserMailer < ActionMailer::Base
|
|||
mail(to: user.email, subject: "Please see the Terms and Conditions attached", delivery_method_options: delivery_options)
|
||||
end
|
||||
end
|
||||
</ruby>
|
||||
```
|
||||
|
||||
h3. Receiving Emails
|
||||
=======
|
||||
Receiving Emails
|
||||
----------------
|
||||
>>>>>>> Convert heading tags and heading section
|
||||
|
||||
Receiving and parsing emails with Action Mailer can be a rather complex endeavor. Before your email reaches your Rails app, you would have had to configure your system to somehow forward emails to your app, which needs to be listening for that. So, to receive emails in your Rails app you'll need to:
|
||||
|
||||
* Implement a +receive+ method in your mailer.
|
||||
* Implement a `receive` method in your mailer.
|
||||
|
||||
* Configure your email server to forward emails from the address(es) you would like your app to receive to +/path/to/app/script/rails runner 'UserMailer.receive(STDIN.read)'+.
|
||||
* Configure your email server to forward emails from the address(es) you would like your app to receive to `/path/to/app/script/rails runner 'UserMailer.receive(STDIN.read)'`.
|
||||
|
||||
Once a method called +receive+ is defined in any mailer, Action Mailer will parse the raw incoming email into an email object, decode it, instantiate a new mailer, and pass the email object to the mailer +receive+ instance method. Here's an example:
|
||||
Once a method called `receive` is defined in any mailer, Action Mailer will parse the raw incoming email into an email object, decode it, instantiate a new mailer, and pass the email object to the mailer `receive` instance method. Here's an example:
|
||||
|
||||
```ruby
|
||||
class UserMailer < ActionMailer::Base
|
||||
|
@ -474,19 +470,21 @@ Action Mailer Configuration
|
|||
|
||||
The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc...)
|
||||
|
||||
|+template_root+|Determines the base from which template references will be made.|
|
||||
|+logger+|Generates information on the mailing run if available. Can be set to +nil+ for no logging. Compatible with both Ruby's own +Logger+ and +Log4r+ loggers.|
|
||||
|+smtp_settings+|Allows detailed configuration for <tt>:smtp</tt> delivery method:<ul><li><tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li><tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li><tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.</li><li><tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.</li><li><tt>:password</tt> - If your mail server requires authentication, set the password in this setting.</li><li><tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.</li><li><tt>:enable_starttls_auto</tt> - Set this to <tt>false</tt> if there is a problem with your server certificate that you cannot resolve.</li></ul>|
|
||||
|+sendmail_settings+|Allows you to override options for the <tt>:sendmail</tt> delivery method.<ul><li><tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.</li><li><tt>:arguments</tt> - The command line arguments to be passed to sendmail. Defaults to <tt>-i -t</tt>.</li></ul>|
|
||||
|+raise_delivery_errors+|Whether or not errors should be raised if the email fails to be delivered.|
|
||||
|+delivery_method+|Defines a delivery method. Possible values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, <tt>:file</tt> and <tt>:test</tt>.|
|
||||
|+perform_deliveries+|Determines whether deliveries are actually carried out when the +deliver+ method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing.|
|
||||
|+deliveries+|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.|
|
||||
|+default_options+|Allows you to set default values for the <tt>mail</tt> method options (<tt>:from</tt>, <tt>:reply_to</tt>, etc.).|
|
||||
|`template_root`|Determines the base from which template references will be made.|
|
||||
|`logger`|Generates information on the mailing run if available. Can be set to `nil` for no logging. Compatible with both Ruby's own `Logger` and `Log4r` loggers.|
|
||||
|`smtp_settings`|Allows detailed configuration for `:smtp` delivery method:<ul><li>`:address` - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li>`:port` - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li>`:domain` - If you need to specify a HELO domain, you can do it here.</li><li>`:user_name` - If your mail server requires authentication, set the username in this setting.</li><li>`:password` - If your mail server requires authentication, set the password in this setting.</li><li>`:authentication` - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of `:plain`, `:login`, `:cram_md5`.</li><li>`:enable_starttls_auto` - Set this to `false` if there is a problem with your server certificate that you cannot resolve.</li></ul>|
|
||||
|`sendmail_settings`|Allows you to override options for the `:sendmail` delivery method.<ul><li>`:location` - The location of the sendmail executable. Defaults to `/usr/sbin/sendmail`.</li><li>`:arguments` - The command line arguments to be passed to sendmail. Defaults to `-i -t`.</li></ul>|
|
||||
|`raise_delivery_errors`|Whether or not errors should be raised if the email fails to be delivered.|
|
||||
|`delivery_method`|Defines a delivery method. Possible values are `:smtp` (default), `:sendmail`, `:file` and `:test`.|
|
||||
|`perform_deliveries`|Determines whether deliveries are actually carried out when the `deliver` method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing.|
|
||||
|`deliveries`|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.|
|
||||
|`default_options`|Allows you to set default values for the `mail` method options (`:from`, `:reply_to`, etc.).|
|
||||
|`async`|Setting this flag will turn on asynchronous message sending, message rendering and delivery will be pushed to `Rails.queue` for processing.|
|
||||
|`default_options`|Allows you to set default values for the `mail` method options (`:from`, `:reply_to`, etc.).|
|
||||
|
||||
### Example Action Mailer Configuration
|
||||
|
||||
An example would be adding the following to your appropriate <tt>config/environments/$RAILS_ENV.rb</tt> file:
|
||||
An example would be adding the following to your appropriate `config/environments/$RAILS_ENV.rb` file:
|
||||
|
||||
```ruby
|
||||
config.action_mailer.delivery_method = :sendmail
|
||||
|
@ -502,7 +500,7 @@ config.action_mailer.default_options = {from: "no-replay@example.org"}
|
|||
|
||||
### Action Mailer Configuration for GMail
|
||||
|
||||
As Action Mailer now uses the Mail gem, this becomes as simple as adding to your <tt>config/environments/$RAILS_ENV.rb</tt> file:
|
||||
As Action Mailer now uses the Mail gem, this becomes as simple as adding to your `config/environments/$RAILS_ENV.rb` file:
|
||||
|
||||
```ruby
|
||||
config.action_mailer.delivery_method = :smtp
|
||||
|
@ -519,7 +517,7 @@ config.action_mailer.smtp_settings = {
|
|||
Mailer Testing
|
||||
--------------
|
||||
|
||||
By default Action Mailer does not send emails in the test environment. They are just added to the +ActionMailer::Base.deliveries+ array.
|
||||
By default Action Mailer does not send emails in the test environment. They are just added to the `ActionMailer::Base.deliveries` array.
|
||||
|
||||
Testing mailers normally involves two things: One is that the mail was queued, and the other one that the email is correct. With that in mind, we could test our example mailer from above like so:
|
||||
|
||||
|
@ -541,7 +539,7 @@ class UserMailerTest < ActionMailer::TestCase
|
|||
end
|
||||
```
|
||||
|
||||
In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain what we expect.
|
||||
In the test we send the email and store the returned object in the `email` variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain what we expect.
|
||||
|
||||
Asynchronous
|
||||
------------
|
||||
|
@ -550,7 +548,7 @@ Rails provides a Synchronous Queue by default. If you want to use an Asynchronou
|
|||
|
||||
### Custom Queues
|
||||
|
||||
If you need a different queue than <tt>Rails.queue</tt> for your mailer you can use <tt>ActionMailer::Base.queue=</tt>:
|
||||
If you need a different queue than `Rails.queue` for your mailer you can use `ActionMailer::Base.queue=`:
|
||||
|
||||
```ruby
|
||||
class WelcomeMailer < ActionMailer::Base
|
||||
|
@ -558,10 +556,10 @@ class WelcomeMailer < ActionMailer::Base
|
|||
end
|
||||
```
|
||||
|
||||
or adding to your <tt>config/environments/$RAILS_ENV.rb</tt>:
|
||||
or adding to your `config/environments/$RAILS_ENV.rb`:
|
||||
|
||||
```ruby
|
||||
config.action_mailer.queue = MyQueue.new
|
||||
```
|
||||
|
||||
Your custom queue should expect a job that responds to <tt>#run</tt>.
|
||||
Your custom queue should expect a job that responds to `#run`.
|
||||
|
|
|
@ -23,7 +23,7 @@ NOTE. Some features of Action View are tied to Active Record, but that doesn't m
|
|||
Using Action View with Rails
|
||||
----------------------------
|
||||
|
||||
For each controller there is an associated directory in the <tt>app/views</tt> directory which holds the template files that make up the views associated with that controller. These files are used to display the view that results from each controller action.
|
||||
For each controller there is an associated directory in the `app/views` directory which holds the template files that make up the views associated with that controller. These files are used to display the view that results from each controller action.
|
||||
|
||||
Let's take a look at what Rails does by default when creating a new resource using the scaffold generator:
|
||||
|
||||
|
@ -43,7 +43,7 @@ $ rails generate scaffold post
|
|||
```
|
||||
|
||||
There is a naming convention for views in Rails. Typically, the views share their name with the associated controller action, as you can see above.
|
||||
For example, the index controller action of the <tt>posts_controller.rb</tt> will use the <tt>index.html.erb</tt> view file in the <tt>app/views/posts</tt> directory.
|
||||
For example, the index controller action of the `posts_controller.rb` will use the `index.html.erb` view file in the `app/views/posts` directory.
|
||||
The complete HTML returned to the client is composed of a combination of this ERB file, a layout template that wraps it, and all the partials that the view may reference. Later on this guide you can find a more detailed documentation of each one of this three components.
|
||||
|
||||
Using Action View outside of Rails
|
||||
|
@ -123,9 +123,9 @@ Find below a brief overview of each one of them.
|
|||
|
||||
### Templates
|
||||
|
||||
Action View templates can be written in several ways. If the template file has a <tt>.erb</tt> extension then it uses a mixture of ERB (included in Ruby) and HTML. If the template file has a <tt>.builder</tt> extension then a fresh instance of <tt>Builder::XmlMarkup</tt> library is used.
|
||||
Action View templates can be written in several ways. If the template file has a `.erb` extension then it uses a mixture of ERB (included in Ruby) and HTML. If the template file has a `.builder` extension then a fresh instance of `Builder::XmlMarkup` library is used.
|
||||
|
||||
Rails supports multiple template systems and uses a file extension to distinguish amongst them. For example, an HTML file using the ERB template system will have <tt>.html.erb</tt> as a file extension.
|
||||
Rails supports multiple template systems and uses a file extension to distinguish amongst them. For example, an HTML file using the ERB template system will have `.html.erb` as a file extension.
|
||||
|
||||
#### ERB
|
||||
|
||||
|
@ -151,7 +151,7 @@ To suppress leading and trailing whitespaces, you can use +<%-+ +-%>+ interchang
|
|||
|
||||
#### Builder
|
||||
|
||||
Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object named +xml+ is automatically made available to templates with a <tt>.builder</tt> extension.
|
||||
Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object named +xml+ is automatically made available to templates with a `.builder` extension.
|
||||
|
||||
Here are some basic examples:
|
||||
|
||||
|
@ -259,25 +259,25 @@ Here, the +_ad_banner.html.erb+ and +_footer.html.erb+ partials could contain co
|
|||
|
||||
#### The :as and :object options
|
||||
|
||||
By default <tt>ActionView::Partials::PartialRenderer</tt> has its object in a local variable with the same name as the template. So, given
|
||||
By default `ActionView::Partials::PartialRenderer` has its object in a local variable with the same name as the template. So, given
|
||||
|
||||
```erb
|
||||
<%= render :partial => "product" %>
|
||||
```
|
||||
|
||||
within product we'll get <tt>@product</tt> in the local variable +product+, as if we had written:
|
||||
within product we'll get `@product` in the local variable +product+, as if we had written:
|
||||
|
||||
```erb
|
||||
<%= render :partial => "product", :locals => { :product => @product } %>
|
||||
```
|
||||
|
||||
With the <tt>:as</tt> option we can specify a different name for said local variable. For example, if we wanted it to be +item+ instead of product+ we'd do:
|
||||
With the `:as` option we can specify a different name for said local variable. For example, if we wanted it to be +item+ instead of product+ we'd do:
|
||||
|
||||
```erb
|
||||
<%= render :partial => "product", :as => 'item' %>
|
||||
```
|
||||
|
||||
The <tt>:object</tt> option can be used to directly specify which object is rendered into the partial; useful when the template's object is elsewhere, in a different ivar or in a local variable for instance.
|
||||
The `:object` option can be used to directly specify which object is rendered into the partial; useful when the template's object is elsewhere, in a different ivar or in a local variable for instance.
|
||||
|
||||
For example, instead of:
|
||||
|
||||
|
@ -291,7 +291,7 @@ you'd do:
|
|||
<%= render :partial => "product", :object => @item %>
|
||||
```
|
||||
|
||||
The <tt>:object</tt> and <tt>:as</tt> options can be used together.
|
||||
The `:object` and `:as` options can be used together.
|
||||
|
||||
#### Rendering Collections
|
||||
|
||||
|
@ -1148,7 +1148,7 @@ Sample usage (selecting the associated Author for an instance of Post, +@post+):
|
|||
collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => true})
|
||||
```
|
||||
|
||||
If <tt>@post.author_id</tt> is 1, this would return:
|
||||
If `@post.author_id` is 1, this would return:
|
||||
|
||||
```html
|
||||
<select name="post[author_id]">
|
||||
|
@ -1184,7 +1184,7 @@ Sample usage (selecting the associated Author for an instance of Post, +@post+):
|
|||
collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial)
|
||||
```
|
||||
|
||||
If <tt>@post.author_id</tt> is 1, this would return:
|
||||
If `@post.author_id` is 1, this would return:
|
||||
|
||||
```html
|
||||
<input id="post_author_id_1" name="post[author_id]" type="radio" value="1" checked="checked" />
|
||||
|
@ -1220,7 +1220,7 @@ Sample usage (selecting the associated Authors for an instance of Post, +@post+)
|
|||
collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial)
|
||||
```
|
||||
|
||||
If <tt>@post.author_ids</tt> is <tt><notextile>[1]</notextile></tt>, this would return:
|
||||
If `@post.author_ids` is [1], this would return:
|
||||
|
||||
```html
|
||||
<input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" checked="checked" />
|
||||
|
@ -1320,7 +1320,7 @@ Example:
|
|||
select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })
|
||||
```
|
||||
|
||||
If <tt>@post.person_id</tt> is 1, this would become:
|
||||
If `@post.person_id` is 1, this would become:
|
||||
|
||||
```html
|
||||
<select name="post[person_id]">
|
||||
|
|
|
@ -77,9 +77,9 @@ The methods are:
|
|||
* +uniq+
|
||||
* +where+
|
||||
|
||||
All of the above methods return an instance of <tt>ActiveRecord::Relation</tt>.
|
||||
All of the above methods return an instance of `ActiveRecord::Relation`.
|
||||
|
||||
The primary operation of <tt>Model.find(options)</tt> can be summarized as:
|
||||
The primary operation of `Model.find(options)` can be summarized as:
|
||||
|
||||
* Convert the supplied options to an equivalent SQL query.
|
||||
* Fire the SQL query and retrieve the corresponding results from the database.
|
||||
|
@ -92,7 +92,7 @@ Active Record provides five different ways of retrieving a single object.
|
|||
|
||||
#### Using a Primary Key
|
||||
|
||||
Using <tt>Model.find(primary_key)</tt>, you can retrieve the object corresponding to the specified _primary key_ that matches any supplied options. For example:
|
||||
Using `Model.find(primary_key)`, you can retrieve the object corresponding to the specified _primary key_ that matches any supplied options. For example:
|
||||
|
||||
```ruby
|
||||
# Find the client with primary key (id) 10.
|
||||
|
@ -106,11 +106,11 @@ The SQL equivalent of the above is:
|
|||
SELECT * FROM clients WHERE (clients.id = 10) LIMIT 1
|
||||
```
|
||||
|
||||
<tt>Model.find(primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception if no matching record is found.
|
||||
`Model.find(primary_key)` will raise an +ActiveRecord::RecordNotFound+ exception if no matching record is found.
|
||||
|
||||
#### +take+
|
||||
|
||||
<tt>Model.take</tt> retrieves a record without any implicit ordering. For example:
|
||||
`Model.take` retrieves a record without any implicit ordering. For example:
|
||||
|
||||
```ruby
|
||||
client = Client.take
|
||||
|
@ -123,13 +123,13 @@ The SQL equivalent of the above is:
|
|||
SELECT * FROM clients LIMIT 1
|
||||
```
|
||||
|
||||
<tt>Model.take</tt> returns +nil+ if no record is found and no exception will be raised.
|
||||
`Model.take` returns +nil+ if no record is found and no exception will be raised.
|
||||
|
||||
TIP: The retrieved record may vary depending on the database engine.
|
||||
|
||||
#### +first+
|
||||
|
||||
<tt>Model.first</tt> finds the first record ordered by the primary key. For example:
|
||||
`Model.first` finds the first record ordered by the primary key. For example:
|
||||
|
||||
```ruby
|
||||
client = Client.first
|
||||
|
@ -142,11 +142,11 @@ The SQL equivalent of the above is:
|
|||
SELECT * FROM clients ORDER BY clients.id ASC LIMIT 1
|
||||
```
|
||||
|
||||
<tt>Model.first</tt> returns +nil+ if no matching record is found and no exception will be raised.
|
||||
`Model.first` returns +nil+ if no matching record is found and no exception will be raised.
|
||||
|
||||
#### +last+
|
||||
|
||||
<tt>Model.last</tt> finds the last record ordered by the primary key. For example:
|
||||
`Model.last` finds the last record ordered by the primary key. For example:
|
||||
|
||||
```ruby
|
||||
client = Client.last
|
||||
|
@ -159,11 +159,11 @@ The SQL equivalent of the above is:
|
|||
SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
|
||||
```
|
||||
|
||||
<tt>Model.last</tt> returns +nil+ if no matching record is found and no exception will be raised.
|
||||
`Model.last` returns +nil+ if no matching record is found and no exception will be raised.
|
||||
|
||||
#### +find_by+
|
||||
|
||||
<tt>Model.find_by</tt> finds the first record matching some conditions. For example:
|
||||
`Model.find_by` finds the first record matching some conditions. For example:
|
||||
|
||||
```ruby
|
||||
Client.find_by first_name: 'Lifo'
|
||||
|
@ -181,7 +181,7 @@ Client.where(first_name: 'Lifo').take
|
|||
|
||||
#### +take!+
|
||||
|
||||
<tt>Model.take!</tt> retrieves a record without any implicit ordering. For example:
|
||||
`Model.take!` retrieves a record without any implicit ordering. For example:
|
||||
|
||||
```ruby
|
||||
client = Client.take!
|
||||
|
@ -194,11 +194,11 @@ The SQL equivalent of the above is:
|
|||
SELECT * FROM clients LIMIT 1
|
||||
```
|
||||
|
||||
<tt>Model.take!</tt> raises +ActiveRecord::RecordNotFound+ if no matching record is found.
|
||||
`Model.take!` raises +ActiveRecord::RecordNotFound+ if no matching record is found.
|
||||
|
||||
#### +first!+
|
||||
|
||||
<tt>Model.first!</tt> finds the first record ordered by the primary key. For example:
|
||||
`Model.first!` finds the first record ordered by the primary key. For example:
|
||||
|
||||
```ruby
|
||||
client = Client.first!
|
||||
|
@ -211,11 +211,11 @@ The SQL equivalent of the above is:
|
|||
SELECT * FROM clients ORDER BY clients.id ASC LIMIT 1
|
||||
```
|
||||
|
||||
<tt>Model.first!</tt> raises +ActiveRecord::RecordNotFound+ if no matching record is found.
|
||||
`Model.first!` raises +ActiveRecord::RecordNotFound+ if no matching record is found.
|
||||
|
||||
#### +last!+
|
||||
|
||||
<tt>Model.last!</tt> finds the last record ordered by the primary key. For example:
|
||||
`Model.last!` finds the last record ordered by the primary key. For example:
|
||||
|
||||
```ruby
|
||||
client = Client.last!
|
||||
|
@ -228,11 +228,11 @@ The SQL equivalent of the above is:
|
|||
SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
|
||||
```
|
||||
|
||||
<tt>Model.last!</tt> raises +ActiveRecord::RecordNotFound+ if no matching record is found.
|
||||
`Model.last!` raises +ActiveRecord::RecordNotFound+ if no matching record is found.
|
||||
|
||||
#### +find_by!+
|
||||
|
||||
<tt>Model.find_by!</tt> finds the first record matching some conditions. It raises +ActiveRecord::RecordNotFound+ if no matching record is found. For example:
|
||||
`Model.find_by!` finds the first record matching some conditions. It raises +ActiveRecord::RecordNotFound+ if no matching record is found. For example:
|
||||
|
||||
```ruby
|
||||
Client.find_by! first_name: 'Lifo'
|
||||
|
@ -252,7 +252,7 @@ Client.where(first_name: 'Lifo').take!
|
|||
|
||||
#### Using Multiple Primary Keys
|
||||
|
||||
<tt>Model.find(array_of_primary_key)</tt> accepts an array of _primary keys_, returning an array containing all of the matching records for the supplied _primary keys_. For example:
|
||||
`Model.find(array_of_primary_key)` accepts an array of _primary keys_, returning an array containing all of the matching records for the supplied _primary keys_. For example:
|
||||
|
||||
```ruby
|
||||
# Find the clients with primary keys 1 and 10.
|
||||
|
@ -266,11 +266,11 @@ The SQL equivalent of the above is:
|
|||
SELECT * FROM clients WHERE (clients.id IN (1,10))
|
||||
```
|
||||
|
||||
WARNING: <tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
|
||||
WARNING: `Model.find(array_of_primary_key)` will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
|
||||
|
||||
#### take
|
||||
|
||||
<tt>Model.take(limit)</tt> retrieves the first number of records specified by +limit+ without any explicit ordering:
|
||||
`Model.take(limit)` retrieves the first number of records specified by +limit+ without any explicit ordering:
|
||||
|
||||
```ruby
|
||||
Client.take(2)
|
||||
|
@ -286,7 +286,7 @@ SELECT * FROM clients LIMIT 2
|
|||
|
||||
#### first
|
||||
|
||||
<tt>Model.first(limit)</tt> finds the first number of records specified by +limit+ ordered by primary key:
|
||||
`Model.first(limit)` finds the first number of records specified by +limit+ ordered by primary key:
|
||||
|
||||
```ruby
|
||||
Client.first(2)
|
||||
|
@ -302,7 +302,7 @@ SELECT * FROM clients LIMIT 2
|
|||
|
||||
#### last
|
||||
|
||||
<tt>Model.last(limit)</tt> finds the number of records specified by +limit+ ordered by primary key in descending order:
|
||||
`Model.last(limit)` finds the number of records specified by +limit+ ordered by primary key in descending order:
|
||||
|
||||
```ruby
|
||||
Client.last(2)
|
||||
|
@ -373,7 +373,7 @@ User.find_each(:start => 2000, :batch_size => 5000) do |user|
|
|||
end
|
||||
```
|
||||
|
||||
Another example would be if you wanted multiple workers handling the same processing queue. You could have each worker handle 10000 records by setting the appropriate <tt>:start</tt> option on each worker.
|
||||
Another example would be if you wanted multiple workers handling the same processing queue. You could have each worker handle 10000 records by setting the appropriate `:start` option on each worker.
|
||||
|
||||
NOTE: The +:include+ option allows you to name associations that should be loaded alongside with the models.
|
||||
|
||||
|
@ -542,7 +542,7 @@ Client.order("orders_count ASC").order("created_at DESC")
|
|||
Selecting Specific Fields
|
||||
-------------------------
|
||||
|
||||
By default, <tt>Model.find</tt> selects all the fields from the result set using +select *+.
|
||||
By default, `Model.find` selects all the fields from the result set using +select *+.
|
||||
|
||||
To select only a subset of fields from the result set, you can specify the subset via the +select+ method.
|
||||
|
||||
|
@ -818,7 +818,7 @@ c2.save # Raises an ActiveRecord::StaleObjectError
|
|||
|
||||
You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, or otherwise apply the business logic needed to resolve the conflict.
|
||||
|
||||
This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
|
||||
This behavior can be turned off by setting `ActiveRecord::Base.lock_optimistically = false`.
|
||||
|
||||
To override the name of the +lock_version+ column, +ActiveRecord::Base+ provides a class attribute called +locking_column+:
|
||||
|
||||
|
@ -1221,11 +1221,11 @@ For every field (also known as an attribute) you define in your table, Active Re
|
|||
|
||||
You can also use +find_last_by_*+ methods which will find the last record matching your argument.
|
||||
|
||||
You can specify an exclamation point (<tt>!</tt>) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+
|
||||
You can specify an exclamation point (`!`) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+
|
||||
|
||||
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 <tt>Client.find_by_name_and_locked("Ryan")</tt>, 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+.
|
||||
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
|
||||
--------------------------
|
||||
|
@ -1327,7 +1327,7 @@ Client.find_by_sql("SELECT * FROM clients
|
|||
+select_all+
|
||||
------------
|
||||
|
||||
<tt>find_by_sql</tt> has a close relative called +connection#select_all+. +select_all+ will retrieve objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
|
||||
`find_by_sql` has a close relative called +connection#select_all+. +select_all+ will retrieve objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
|
||||
|
||||
```ruby
|
||||
Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
|
||||
|
@ -1336,7 +1336,7 @@ Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
|
|||
+pluck+
|
||||
-------
|
||||
|
||||
<tt>pluck</tt> can be used to query a single or multiple columns from the underlying table of a model. It accepts a list of column names as argument and returns an array of values of the specified columns with the corresponding data type.
|
||||
`pluck` can be used to query a single or multiple columns from the underlying table of a model. It accepts a list of column names as argument and returns an array of values of the specified columns with the corresponding data type.
|
||||
|
||||
```ruby
|
||||
Client.where(:active => true).pluck(:id)
|
||||
|
|
|
@ -299,7 +299,7 @@ The possible length constraint options are:
|
|||
* +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a range.
|
||||
* +:is+ - The attribute length must be equal to the given value.
|
||||
|
||||
The default error messages depend on the type of length validation being performed. You can personalize these messages using the +:wrong_length+, +:too_long+, and +:too_short+ options and <tt>%{count}</tt> as a placeholder for the number corresponding to the length constraint being used. You can still use the +:message+ option to specify an error message.
|
||||
The default error messages depend on the type of length validation being performed. You can personalize these messages using the +:wrong_length+, +:too_long+, and +:too_short+ options and `%{count}` as a placeholder for the number corresponding to the length constraint being used. You can still use the +:message+ option to specify an error message.
|
||||
|
||||
```ruby
|
||||
class Person < ActiveRecord::Base
|
||||
|
@ -380,7 +380,7 @@ end
|
|||
|
||||
If you validate the presence of an object associated via a +has_one+ or +has_many+ relationship, it will check that the object is neither +blank?+ nor +marked_for_destruction?+.
|
||||
|
||||
Since +false.blank?+ is true, if you want to validate the presence of a boolean field you should use <tt>validates :field_name, :inclusion => { :in => [true, false] }</tt>.
|
||||
Since +false.blank?+ is true, if you want to validate the presence of a boolean field you should use `validates :field_name, :inclusion => { :in => [true, false] }`.
|
||||
|
||||
The default error message is "_can't be empty_".
|
||||
|
||||
|
@ -624,7 +624,7 @@ When the built-in validation helpers are not enough for your needs, you can writ
|
|||
|
||||
### Custom Validators
|
||||
|
||||
Custom validators are classes that extend <tt>ActiveModel::Validator</tt>. These classes must implement a +validate+ method which takes a record as an argument and performs the validation on it. The custom validator is called using the +validates_with+ method.
|
||||
Custom validators are classes that extend `ActiveModel::Validator`. These classes must implement a +validate+ method which takes a record as an argument and performs the validation on it. The custom validator is called using the +validates_with+ method.
|
||||
|
||||
```ruby
|
||||
class MyValidator < ActiveModel::Validator
|
||||
|
@ -641,7 +641,7 @@ class Person
|
|||
end
|
||||
```
|
||||
|
||||
The easiest way to add custom validators for validating individual attributes is with the convenient <tt>ActiveModel::EachValidator</tt>. In this case, the custom validator class must implement a +validate_each+ method which takes three arguments: record, attribute and value which correspond to the instance, the attribute to be validated and the value of the attribute in the passed instance.
|
||||
The easiest way to add custom validators for validating individual attributes is with the convenient `ActiveModel::EachValidator`. In this case, the custom validator class must implement a +validate_each+ method which takes three arguments: record, attribute and value which correspond to the instance, the attribute to be validated and the value of the attribute in the passed instance.
|
||||
|
||||
```ruby
|
||||
class EmailValidator < ActiveModel::EachValidator
|
||||
|
|
|
@ -87,7 +87,7 @@ The following values are considered to be blank in a Rails application:
|
|||
|
||||
* any other object that responds to +empty?+ and it is empty.
|
||||
|
||||
INFO: The predicate for strings uses the Unicode-aware character class <tt>[:space:]</tt>, so for example U+2029 (paragraph separator) is considered to be whitespace.
|
||||
INFO: The predicate for strings uses the Unicode-aware character class `[:space:]`, so for example U+2029 (paragraph separator) is considered to be whitespace.
|
||||
|
||||
WARNING: Note that numbers are not mentioned, in particular 0 and 0.0 are *not* blank.
|
||||
|
||||
|
@ -348,7 +348,7 @@ account.to_query('company[name]')
|
|||
|
||||
so its output is ready to be used in a query string.
|
||||
|
||||
Arrays return the result of applying +to_query+ to each element with <tt>_key_[]</tt> as key, and join the result with "&":
|
||||
Arrays return the result of applying +to_query+ to each element with `_key_[]` as key, and join the result with "&":
|
||||
|
||||
```ruby
|
||||
[3.4, -45.6].to_query('sample')
|
||||
|
@ -1124,7 +1124,7 @@ NOTE: Defined in +active_support/core_ext/class/subclasses.rb+.
|
|||
|
||||
#### +descendants+
|
||||
|
||||
The +descendants+ method returns all classes that are <tt><</tt> than its receiver:
|
||||
The +descendants+ method returns all classes that are `<` than its receiver:
|
||||
|
||||
```ruby
|
||||
class C; end
|
||||
|
@ -1180,7 +1180,7 @@ s # => "<script>...</script>"
|
|||
|
||||
It is your responsibility to ensure calling +html_safe+ on a particular string is fine.
|
||||
|
||||
If you append onto a safe string, either in-place with +concat+/<tt><<</tt>, or with <tt>+</tt>, the result is a safe string. Unsafe arguments are escaped:
|
||||
If you append onto a safe string, either in-place with +concat+/`<<`, or with `+`, the result is a safe string. Unsafe arguments are escaped:
|
||||
|
||||
```ruby
|
||||
"".html_safe + "<" # => "<"
|
||||
|
@ -1204,7 +1204,7 @@ To insert something verbatim use the +raw+ helper rather than calling +html_safe
|
|||
<%= raw @cms.current_template %> <%# inserts @cms.current_template as is %>
|
||||
```
|
||||
|
||||
or, equivalently, use <tt><%==</tt>:
|
||||
or, equivalently, use `<%==`:
|
||||
|
||||
```erb
|
||||
<%== @cms.current_template %> <%# inserts @cms.current_template as is %>
|
||||
|
@ -1288,7 +1288,7 @@ NOTE: Defined in +active_support/core_ext/string/filters.rb+.
|
|||
|
||||
### +inquiry+
|
||||
|
||||
The <tt>inquiry</tt> method converts a string into a +StringInquirer+ object making equality checks prettier.
|
||||
The `inquiry` method converts a string into a +StringInquirer+ object making equality checks prettier.
|
||||
|
||||
```ruby
|
||||
"production".inquiry.production? # => true
|
||||
|
@ -1433,7 +1433,7 @@ The method +pluralize+ returns the plural of its receiver:
|
|||
|
||||
As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in +config/initializers/inflections.rb+. That file is generated by the +rails+ command and has instructions in comments.
|
||||
|
||||
+pluralize+ can also take an optional +count+ parameter. If <tt>count == 1</tt> the singular form will be returned. For any other value of +count+ the plural form will be returned:
|
||||
+pluralize+ can also take an optional +count+ parameter. If `count == 1` the singular form will be returned. For any other value of +count+ the plural form will be returned:
|
||||
|
||||
```ruby
|
||||
"dude".pluralize(0) # => "dudes"
|
||||
|
@ -1511,7 +1511,7 @@ end
|
|||
|
||||
That may be handy to compute method names in a language that follows that convention, for example JavaScript.
|
||||
|
||||
INFO: As a rule of thumb you can think of +camelize+ as the inverse of +underscore+, though there are cases where that does not hold: <tt>"SSLError".underscore.camelize</tt> gives back <tt>"SslError"</tt>. To support cases such as this, Active Support allows you to specify acronyms in +config/initializers/inflections.rb+:
|
||||
INFO: As a rule of thumb you can think of +camelize+ as the inverse of +underscore+, though there are cases where that does not hold: `"SSLError".underscore.camelize` gives back `"SslError"`. To support cases such as this, Active Support allows you to specify acronyms in +config/initializers/inflections.rb+:
|
||||
|
||||
```ruby
|
||||
ActiveSupport::Inflector.inflections do |inflect|
|
||||
|
@ -1560,7 +1560,7 @@ def load_missing_constant(from_mod, const_name)
|
|||
end
|
||||
```
|
||||
|
||||
INFO: As a rule of thumb you can think of +underscore+ as the inverse of +camelize+, though there are cases where that does not hold. For example, <tt>"SSLError".underscore.camelize</tt> gives back <tt>"SslError"</tt>.
|
||||
INFO: As a rule of thumb you can think of +underscore+ as the inverse of +camelize+, though there are cases where that does not hold. For example, `"SSLError".underscore.camelize` gives back `"SslError"`.
|
||||
|
||||
NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
|
||||
|
||||
|
@ -2038,7 +2038,7 @@ The method +sum+ adds the elements of an enumerable:
|
|||
(1..100).sum # => 5050
|
||||
```
|
||||
|
||||
Addition only assumes the elements respond to <tt>+</tt>:
|
||||
Addition only assumes the elements respond to `+`:
|
||||
|
||||
```ruby
|
||||
[[1, 2], [2, 3], [3, 4]].sum # => [1, 2, 2, 3, 3, 4]
|
||||
|
@ -2152,7 +2152,7 @@ NOTE: Defined in +active_support/core_ext/array/access.rb+.
|
|||
|
||||
#### +prepend+
|
||||
|
||||
This method is an alias of <tt>Array#unshift</tt>.
|
||||
This method is an alias of `Array#unshift`.
|
||||
|
||||
```ruby
|
||||
%w(a b c d).prepend('e') # => %w(e a b c d)
|
||||
|
@ -2163,7 +2163,7 @@ NOTE: Defined in +active_support/core_ext/array/prepend_and_append.rb+.
|
|||
|
||||
#### +append+
|
||||
|
||||
This method is an alias of <tt>Array#<<</tt>.
|
||||
This method is an alias of `Array#<<`.
|
||||
|
||||
```ruby
|
||||
%w(a b c d).append('e') # => %w(a b c d e)
|
||||
|
@ -2182,7 +2182,7 @@ User.exists?(:email => params[:email])
|
|||
|
||||
That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options.
|
||||
|
||||
If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.
|
||||
If a method expects a variable number of arguments and uses `*` in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.
|
||||
|
||||
In those cases, you may give an options hash a distinguished treatment with +extract_options!+. This method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise it returns an empty hash.
|
||||
|
||||
|
@ -2215,18 +2215,18 @@ The method +to_sentence+ turns an array into a string containing a sentence that
|
|||
|
||||
This method accepts three options:
|
||||
|
||||
* <tt>:two_words_connector</tt>: What is used for arrays of length 2. Default is " and ".
|
||||
* <tt>:words_connector</tt>: What is used to join the elements of arrays with 3 or more elements, except for the last two. Default is ", ".
|
||||
* <tt>:last_word_connector</tt>: What is used to join the last items of an array with 3 or more elements. Default is ", and ".
|
||||
* `:two_words_connector`: What is used for arrays of length 2. Default is " and ".
|
||||
* `:words_connector`: What is used to join the elements of arrays with 3 or more elements, except for the last two. Default is ", ".
|
||||
* `:last_word_connector`: What is used to join the last items of an array with 3 or more elements. Default is ", and ".
|
||||
|
||||
The defaults for these options can be localised, their keys are:
|
||||
|
||||
|_. Option |_. I18n key |
|
||||
| <tt>:two_words_connector</tt> | <tt>support.array.two_words_connector</tt> |
|
||||
| <tt>:words_connector</tt> | <tt>support.array.words_connector</tt> |
|
||||
| <tt>:last_word_connector</tt> | <tt>support.array.last_word_connector</tt> |
|
||||
| `:two_words_connector` | `support.array.two_words_connector` |
|
||||
| `:words_connector` | `support.array.words_connector` |
|
||||
| `:last_word_connector` | `support.array.last_word_connector` |
|
||||
|
||||
Options <tt>:connector</tt> and <tt>:skip_last_comma</tt> are deprecated.
|
||||
Options `:connector` and `:skip_last_comma` are deprecated.
|
||||
|
||||
NOTE: Defined in +active_support/core_ext/array/conversions.rb+.
|
||||
|
||||
|
@ -2234,7 +2234,7 @@ NOTE: Defined in +active_support/core_ext/array/conversions.rb+.
|
|||
|
||||
The method +to_formatted_s+ acts like +to_s+ by default.
|
||||
|
||||
If the array contains items that respond to +id+, however, it may be passed the symbol <tt>:db</tt> as argument. That's typically used with collections of ARs. Returned strings are:
|
||||
If the array contains items that respond to +id+, however, it may be passed the symbol `:db` as argument. That's typically used with collections of ARs. Returned strings are:
|
||||
|
||||
```ruby
|
||||
[].to_formatted_s(:db) # => "null"
|
||||
|
@ -2272,7 +2272,7 @@ Contributor.limit(2).order(:rank).to_xml
|
|||
|
||||
To do so it sends +to_xml+ to every item in turn, and collects the results under a root node. All items must respond to +to_xml+, an exception is raised otherwise.
|
||||
|
||||
By default, the name of the root element is the underscorized and dasherized plural of the name of the class of the first item, provided the rest of elements belong to that type (checked with <tt>is_a?</tt>) and they are not hashes. In the example above that's "contributors".
|
||||
By default, the name of the root element is the underscorized and dasherized plural of the name of the class of the first item, provided the rest of elements belong to that type (checked with `is_a?`) and they are not hashes. In the example above that's "contributors".
|
||||
|
||||
If there's any element that does not belong to the type of the first one the root node becomes "objects":
|
||||
|
||||
|
@ -2319,11 +2319,11 @@ If the receiver is an array of hashes the root element is by default also "objec
|
|||
# </objects>
|
||||
```
|
||||
|
||||
WARNING. If the collection is empty the root element is by default "nil-classes". That's a gotcha, for example the root element of the list of contributors above would not be "contributors" if the collection was empty, but "nil-classes". You may use the <tt>:root</tt> option to ensure a consistent root element.
|
||||
WARNING. If the collection is empty the root element is by default "nil-classes". That's a gotcha, for example the root element of the list of contributors above would not be "contributors" if the collection was empty, but "nil-classes". You may use the `:root` option to ensure a consistent root element.
|
||||
|
||||
The name of children nodes is by default the name of the root node singularized. In the examples above we've seen "contributor" and "object". The option <tt>:children</tt> allows you to set these node names.
|
||||
The name of children nodes is by default the name of the root node singularized. In the examples above we've seen "contributor" and "object". The option `:children` allows you to set these node names.
|
||||
|
||||
The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can configure your own builder via the <tt>:builder</tt> option. The method also accepts options like <tt>:dasherize</tt> and friends, they are forwarded to the builder:
|
||||
The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder via the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder:
|
||||
|
||||
```ruby
|
||||
Contributor.limit(2).order(:rank).to_xml(:skip_types => true)
|
||||
|
@ -2363,10 +2363,10 @@ Array.wrap([1, 2, 3]) # => [1, 2, 3]
|
|||
Array.wrap(0) # => [0]
|
||||
```
|
||||
|
||||
This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences:
|
||||
This method is similar in purpose to `Kernel#Array`, but there are some differences:
|
||||
|
||||
* If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt> moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns +nil+ right away.
|
||||
* If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt> raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.
|
||||
* If the argument responds to +to_ary+ the method is invoked. `Kernel#Array` moves on to try +to_a+ if the returned value is +nil+, but `Array.wrap` returns +nil+ right away.
|
||||
* If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, `Kernel#Array` raises an exception, while `Array.wrap` does not, it just returns the value.
|
||||
* It does not call +to_a+ on the argument, though special-cases +nil+ to return an empty array.
|
||||
|
||||
The last point is particularly worth comparing for some enumerables:
|
||||
|
@ -2382,9 +2382,9 @@ There's also a related idiom that uses the splat operator:
|
|||
[*object]
|
||||
```
|
||||
|
||||
which in Ruby 1.8 returns +[nil]+ for +nil+, and calls to <tt>Array(object)</tt> otherwise. (Please if you know the exact behavior in 1.9 contact fxn.)
|
||||
which in Ruby 1.8 returns +[nil]+ for +nil+, and calls to `Array(object)` otherwise. (Please if you know the exact behavior in 1.9 contact fxn.)
|
||||
|
||||
Thus, in this case the behavior is different for +nil+, and the differences with <tt>Kernel#Array</tt> explained above apply to the rest of +object+s.
|
||||
Thus, in this case the behavior is different for +nil+, and the differences with `Kernel#Array` explained above apply to the rest of +object+s.
|
||||
|
||||
NOTE: Defined in +active_support/core_ext/array/wrap.rb+.
|
||||
|
||||
|
@ -2520,15 +2520,15 @@ The method +to_xml+ returns a string containing an XML representation of its rec
|
|||
|
||||
To do so, the method loops over the pairs and builds nodes that depend on the _values_. Given a pair +key+, +value+:
|
||||
|
||||
* If +value+ is a hash there's a recursive call with +key+ as <tt>:root</tt>.
|
||||
* If +value+ is a hash there's a recursive call with +key+ as `:root`.
|
||||
|
||||
* If +value+ is an array there's a recursive call with +key+ as <tt>:root</tt>, and +key+ singularized as <tt>:children</tt>.
|
||||
* If +value+ is an array there's a recursive call with +key+ as `:root`, and +key+ singularized as `:children`.
|
||||
|
||||
* If +value+ is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the +options+ hash as first argument with +key+ as <tt>:root</tt>, and +key+ singularized as second argument. Its return value becomes a new node.
|
||||
* If +value+ is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the +options+ hash as first argument with +key+ as `:root`, and +key+ singularized as second argument. Its return value becomes a new node.
|
||||
|
||||
* If +value+ responds to +to_xml+ the method is invoked with +key+ as <tt>:root</tt>.
|
||||
* If +value+ responds to +to_xml+ the method is invoked with +key+ as `:root`.
|
||||
|
||||
* Otherwise, a node with +key+ as tag is created with a string representation of +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added. Unless the option <tt>:skip_types</tt> exists and is true, an attribute "type" is added as well according to the following mapping:
|
||||
* Otherwise, a node with +key+ as tag is created with a string representation of +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added. Unless the option `:skip_types` exists and is true, an attribute "type" is added as well according to the following mapping:
|
||||
|
||||
```ruby
|
||||
XML_TYPE_NAMES = {
|
||||
|
@ -2545,9 +2545,9 @@ XML_TYPE_NAMES = {
|
|||
}
|
||||
```
|
||||
|
||||
By default the root node is "hash", but that's configurable via the <tt>:root</tt> option.
|
||||
By default the root node is "hash", but that's configurable via the `:root` option.
|
||||
|
||||
The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can configure your own builder with the <tt>:builder</tt> option. The method also accepts options like <tt>:dasherize</tt> and friends, they are forwarded to the builder.
|
||||
The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder with the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder.
|
||||
|
||||
NOTE: Defined in +active_support/core_ext/hash/conversions.rb+.
|
||||
|
||||
|
|
|
@ -103,7 +103,7 @@ You are ready to add some AJAX love to your Rails app!
|
|||
|
||||
### Examples
|
||||
|
||||
To make them working with AJAX, simply pass the <tt>remote: true</tt> option to
|
||||
To make them working with AJAX, simply pass the `remote: true` option to
|
||||
the original non-remote method.
|
||||
|
||||
```ruby
|
||||
|
|
|
@ -52,7 +52,7 @@ Short docs do not need an explicit "Examples" label to introduce snippets; they
|
|||
|
||||
```ruby
|
||||
# Converts a collection of elements into a formatted string by calling
|
||||
# <tt>to_s</tt> on all elements and joining them.
|
||||
# `to_s` on all elements and joining them.
|
||||
#
|
||||
# Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
|
||||
```
|
||||
|
@ -126,15 +126,15 @@ Use fixed-width fonts for:
|
|||
|
||||
```ruby
|
||||
class Array
|
||||
# Calls <tt>to_param</tt> on all its elements and joins the result with
|
||||
# slashes. This is used by <tt>url_for</tt> in Action Pack.
|
||||
# Calls `to_param` on all its elements and joins the result with
|
||||
# slashes. This is used by `url_for` in Action Pack.
|
||||
def to_param
|
||||
collect { |e| e.to_param }.join '/'
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
WARNING: Using a pair of ++...++ for fixed-width font only works with *words*; that is: anything matching <tt>\A\w+\z</tt>. For anything else use +<tt>...</tt>+, notably symbols, setters, inline snippets, etc.
|
||||
WARNING: Using a pair of ++...++ for fixed-width font only works with *words*; that is: anything matching `\A\w+\z`. For anything else use +<tt>...</tt>+, notably symbols, setters, inline snippets, etc.
|
||||
|
||||
### Regular Font
|
||||
|
||||
|
@ -144,11 +144,11 @@ When "true" and "false" are English words rather than Ruby keywords use a regula
|
|||
# Runs all the validations within the specified context. Returns true if no errors are found,
|
||||
# false otherwise.
|
||||
#
|
||||
# If the argument is false (default is +nil+), the context is set to <tt>:create</tt> if
|
||||
# <tt>new_record?</tt> is true, and to <tt>:update</tt> if it is not.
|
||||
# If the argument is false (default is +nil+), the context is set to `:create` if
|
||||
# `new_record?` is true, and to `:update` if it is not.
|
||||
#
|
||||
# Validations with no <tt>:on</tt> option will run no matter the context. Validations with
|
||||
# some <tt>:on</tt> option will only run in the specified context.
|
||||
# Validations with no `:on` option will run no matter the context. Validations with
|
||||
# some `:on` option will only run in the specified context.
|
||||
def valid?(context = nil)
|
||||
...
|
||||
end
|
||||
|
@ -160,7 +160,7 @@ Description Lists
|
|||
In lists of options, parameters, etc. use a hyphen between the item and its description (reads better than a colon because normally options are symbols):
|
||||
|
||||
```ruby
|
||||
# * <tt>:allow_nil</tt> - Skip validation if attribute is <tt>nil</tt>.
|
||||
# * `:allow_nil` - Skip validation if attribute is `nil`.
|
||||
```
|
||||
|
||||
The description starts in upper case and ends with a full stop—it's standard English.
|
||||
|
|
|
@ -27,7 +27,7 @@ In Rails 3.1, the asset pipeline is enabled by default. It can be disabled in +c
|
|||
config.assets.enabled = false
|
||||
```
|
||||
|
||||
You can also disable the asset pipeline while creating a new application by passing the <tt>--skip-sprockets</tt> option.
|
||||
You can also disable the asset pipeline while creating a new application by passing the `--skip-sprockets` option.
|
||||
|
||||
```
|
||||
rails new appname --skip-sprockets
|
||||
|
@ -172,7 +172,7 @@ It is important to note that files you want to reference outside a manifest must
|
|||
|
||||
Sprockets uses files named +index+ (with the relevant extensions) for a special purpose.
|
||||
|
||||
For example, if you have a jQuery library with many modules, which is stored in +lib/assets/library_name+, the file +lib/assets/library_name/index.js+ serves as the manifest for all files in this library. This file could include a list of all the required files in order, or a simple <tt>require_tree</tt> directive.
|
||||
For example, if you have a jQuery library with many modules, which is stored in +lib/assets/library_name+, the file +lib/assets/library_name/index.js+ serves as the manifest for all files in this library. This file could include a list of all the required files in order, or a simple `require_tree` directive.
|
||||
|
||||
The library as a whole can be accessed in the site's application manifest like so:
|
||||
|
||||
|
@ -209,7 +209,7 @@ Images can also be organized into subdirectories if required, and they can be ac
|
|||
<%= image_tag "icons/rails.png" %>
|
||||
```
|
||||
|
||||
WARNING: If you're precompiling your assets (see "In Production":#in-production below), linking to an asset that does not exist will raise an exception in the calling page. This includes linking to a blank string. As such, be careful using <tt>image_tag</tt> and the other helpers with user-supplied data.
|
||||
WARNING: If you're precompiling your assets (see "In Production":#in-production below), linking to an asset that does not exist will raise an exception in the calling page. This includes linking to a blank string. As such, be careful using `image_tag` and the other helpers with user-supplied data.
|
||||
|
||||
#### CSS and ERB
|
||||
|
||||
|
@ -469,7 +469,7 @@ This can be changed with the +config.assets.manifest+ option. A fully specified
|
|||
config.assets.manifest = '/path/to/some/other/location'
|
||||
```
|
||||
|
||||
NOTE: If there are missing precompiled files in production you will get an <tt>Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError</tt> exception indicating the name of the missing file(s).
|
||||
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
|
||||
|
||||
|
@ -541,7 +541,7 @@ There are two caveats:
|
|||
* You must not run the Capistrano deployment task that precompiles assets.
|
||||
* You must change the following two application configuration settings.
|
||||
|
||||
In <tt>config/environments/development.rb</tt>, place the following line:
|
||||
In `config/environments/development.rb`, place the following line:
|
||||
|
||||
```erb
|
||||
config.assets.prefix = "/dev-assets"
|
||||
|
@ -651,7 +651,7 @@ This is a handy option if you are updating an existing project (pre Rails 3.1) t
|
|||
|
||||
The X-Sendfile header is a directive to the web server to ignore the response from the application, and instead serve a specified file from disk. This option is off by default, but can be enabled if your server supports it. When enabled, this passes responsibility for serving the file to the web server, which is faster.
|
||||
|
||||
Apache and nginx support this option, which can be enabled in <tt>config/environments/production.rb</tt>.
|
||||
Apache and nginx support this option, which can be enabled in `config/environments/production.rb`.
|
||||
|
||||
```erb
|
||||
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
|
||||
|
|
|
@ -556,9 +556,9 @@ c.first_name == o.customer.first_name # => true
|
|||
|
||||
There are a few limitations to +inverse_of+ support:
|
||||
|
||||
* They do not work with <tt>:through</tt> associations.
|
||||
* They do not work with <tt>:polymorphic</tt> associations.
|
||||
* They do not work with <tt>:as</tt> associations.
|
||||
* They do not work with `:through` associations.
|
||||
* They do not work with `:polymorphic` associations.
|
||||
* They do not work with `:as` associations.
|
||||
* For +belongs_to+ associations, +has_many+ inverse associations are ignored.
|
||||
|
||||
Detailed Association Reference
|
||||
|
@ -574,12 +574,12 @@ The +belongs_to+ association creates a one-to-one match with another model. In d
|
|||
|
||||
When you declare a +belongs_to+ association, the declaring class automatically gains four methods related to the association:
|
||||
|
||||
* <tt><em>association</em>(force_reload = false)</tt>
|
||||
* <tt><em>association</em>=(associate)</tt>
|
||||
* <tt>build_<em>association</em>(attributes = {})</tt>
|
||||
* <tt>create_<em>association</em>(attributes = {})</tt>
|
||||
* `<em>association</em>(force_reload = false)`
|
||||
* `<em>association</em>=(associate)`
|
||||
* `build_<em>association</em>(attributes = {})`
|
||||
* `create_<em>association</em>(attributes = {})`
|
||||
|
||||
In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to +belongs_to+. For example, given the declaration:
|
||||
In all of these methods, `<em>association</em>` is replaced with the symbol passed as the first argument to +belongs_to+. For example, given the declaration:
|
||||
|
||||
```ruby
|
||||
class Order < ActiveRecord::Base
|
||||
|
@ -598,9 +598,9 @@ create_customer
|
|||
|
||||
NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix.
|
||||
|
||||
##### <tt><em>association</em>(force_reload = false)</tt>
|
||||
##### `<em>association</em>(force_reload = false)`
|
||||
|
||||
The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+.
|
||||
The `<em>association</em>` method returns the associated object, if any. If no associated object is found, it returns +nil+.
|
||||
|
||||
```ruby
|
||||
@customer = @order.customer
|
||||
|
@ -608,26 +608,26 @@ The <tt><em>association</em></tt> method returns the associated object, if any.
|
|||
|
||||
If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument.
|
||||
|
||||
##### <tt>_association_=(associate)</tt>
|
||||
##### `_association_=(associate)`
|
||||
|
||||
The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
|
||||
The `<em>association</em>=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
|
||||
|
||||
```ruby
|
||||
@order.customer = @customer
|
||||
```
|
||||
|
||||
##### <tt>build_<em>association</em>(attributes = {})</tt>
|
||||
##### `build_<em>association</em>(attributes = {})`
|
||||
|
||||
The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
|
||||
The `build_<em>association</em>` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
|
||||
|
||||
```ruby
|
||||
@customer = @order.build_customer(:customer_number => 123,
|
||||
:customer_name => "John Doe")
|
||||
```
|
||||
|
||||
##### <tt>create_<em>association</em>(attributes = {})</tt>
|
||||
##### `create_<em>association</em>(attributes = {})`
|
||||
|
||||
The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through this object's foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
|
||||
The `create_<em>association</em>` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through this object's foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
|
||||
|
||||
```ruby
|
||||
@customer = @order.create_customer(:customer_number => 123,
|
||||
|
@ -852,7 +852,7 @@ TIP: If you use the +select+ method on a +belongs_to+ association, you should al
|
|||
|
||||
#### Do Any Associated Objects Exist?
|
||||
|
||||
You can see if any associated objects exist by using the <tt><em>association</em>.nil?</tt> method:
|
||||
You can see if any associated objects exist by using the `<em>association</em>.nil?` method:
|
||||
|
||||
```ruby
|
||||
if @order.customer.nil?
|
||||
|
@ -872,12 +872,12 @@ The +has_one+ association creates a one-to-one match with another model. In data
|
|||
|
||||
When you declare a +has_one+ association, the declaring class automatically gains four methods related to the association:
|
||||
|
||||
* <tt><em>association</em>(force_reload = false)</tt>
|
||||
* <tt><em>association</em>=(associate)</tt>
|
||||
* <tt>build_<em>association</em>(attributes = {})</tt>
|
||||
* <tt>create_<em>association</em>(attributes = {})</tt>
|
||||
* `<em>association</em>(force_reload = false)`
|
||||
* `<em>association</em>=(associate)`
|
||||
* `build_<em>association</em>(attributes = {})`
|
||||
* `create_<em>association</em>(attributes = {})`
|
||||
|
||||
In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to +has_one+. For example, given the declaration:
|
||||
In all of these methods, `<em>association</em>` is replaced with the symbol passed as the first argument to +has_one+. For example, given the declaration:
|
||||
|
||||
```ruby
|
||||
class Supplier < ActiveRecord::Base
|
||||
|
@ -896,9 +896,9 @@ create_account
|
|||
|
||||
NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix.
|
||||
|
||||
##### <tt><em>association</em>(force_reload = false)</tt>
|
||||
##### `<em>association</em>(force_reload = false)`
|
||||
|
||||
The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+.
|
||||
The `<em>association</em>` method returns the associated object, if any. If no associated object is found, it returns +nil+.
|
||||
|
||||
```ruby
|
||||
@account = @supplier.account
|
||||
|
@ -906,25 +906,25 @@ The <tt><em>association</em></tt> method returns the associated object, if any.
|
|||
|
||||
If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument.
|
||||
|
||||
##### <tt><em>association</em>=(associate)</tt>
|
||||
##### `<em>association</em>=(associate)`
|
||||
|
||||
The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.
|
||||
The `<em>association</em>=` method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.
|
||||
|
||||
```ruby
|
||||
@supplier.account = @account
|
||||
```
|
||||
|
||||
##### <tt>build_<em>association</em>(attributes = {})</tt>
|
||||
##### `build_<em>association</em>(attributes = {})`
|
||||
|
||||
The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.
|
||||
The `build_<em>association</em>` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.
|
||||
|
||||
```ruby
|
||||
@account = @supplier.build_account(:terms => "Net 30")
|
||||
```
|
||||
|
||||
##### <tt>create_<em>association</em>(attributes = {})</tt>
|
||||
##### `create_<em>association</em>(attributes = {})`
|
||||
|
||||
The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
|
||||
The `create_<em>association</em>` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
|
||||
|
||||
```ruby
|
||||
@account = @supplier.create_account(:terms => "Net 30")
|
||||
|
@ -1101,7 +1101,7 @@ The +select+ method lets you override the SQL +SELECT+ clause that is used to re
|
|||
|
||||
#### Do Any Associated Objects Exist?
|
||||
|
||||
You can see if any associated objects exist by using the <tt><em>association</em>.nil?</tt> method:
|
||||
You can see if any associated objects exist by using the `<em>association</em>.nil?` method:
|
||||
|
||||
```ruby
|
||||
if @supplier.account.nil?
|
||||
|
@ -1117,7 +1117,7 @@ If either of these saves fails due to validation errors, then the assignment sta
|
|||
|
||||
If the parent object (the one declaring the +has_one+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved. They will automatically when the parent object is saved.
|
||||
|
||||
If you want to assign an object to a +has_one+ association without saving the object, use the <tt><em>association</em>.build</tt> method.
|
||||
If you want to assign an object to a +has_one+ association without saving the object, use the `<em>association</em>.build` method.
|
||||
|
||||
### +has_many+ Association Reference
|
||||
|
||||
|
@ -1127,22 +1127,22 @@ The +has_many+ association creates a one-to-many relationship with another model
|
|||
|
||||
When you declare a +has_many+ association, the declaring class automatically gains 13 methods related to the association:
|
||||
|
||||
* <tt><em>collection</em>(force_reload = false)</tt>
|
||||
* <tt><em>collection</em><<(object, ...)</tt>
|
||||
* <tt><em>collection</em>.delete(object, ...)</tt>
|
||||
* <tt><em>collection</em>=objects</tt>
|
||||
* <tt><em>collection_singular</em>_ids</tt>
|
||||
* <tt><em>collection_singular</em>_ids=ids</tt>
|
||||
* <tt><em>collection</em>.clear</tt>
|
||||
* <tt><em>collection</em>.empty?</tt>
|
||||
* <tt><em>collection</em>.size</tt>
|
||||
* <tt><em>collection</em>.find(...)</tt>
|
||||
* <tt><em>collection</em>.where(...)</tt>
|
||||
* <tt><em>collection</em>.exists?(...)</tt>
|
||||
* <tt><em>collection</em>.build(attributes = {}, ...)</tt>
|
||||
* <tt><em>collection</em>.create(attributes = {})</tt>
|
||||
* `<em>collection</em>(force_reload = false)`
|
||||
* `<em>collection</em><<(object, ...)`
|
||||
* `<em>collection</em>.delete(object, ...)`
|
||||
* `<em>collection</em>=objects`
|
||||
* `<em>collection_singular</em>_ids`
|
||||
* `<em>collection_singular</em>_ids=ids`
|
||||
* `<em>collection</em>.clear`
|
||||
* `<em>collection</em>.empty?`
|
||||
* `<em>collection</em>.size`
|
||||
* `<em>collection</em>.find(...)`
|
||||
* `<em>collection</em>.where(...)`
|
||||
* `<em>collection</em>.exists?(...)`
|
||||
* `<em>collection</em>.build(attributes = {}, ...)`
|
||||
* `<em>collection</em>.create(attributes = {})`
|
||||
|
||||
In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration:
|
||||
In all of these methods, `<em>collection</em>` is replaced with the symbol passed as the first argument to +has_many+, and `<em>collection_singular</em>` is replaced with the singularized version of that symbol.. For example, given the declaration:
|
||||
|
||||
```ruby
|
||||
class Customer < ActiveRecord::Base
|
||||
|
@ -1169,25 +1169,25 @@ orders.build(attributes = {}, ...)
|
|||
orders.create(attributes = {})
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em>(force_reload = false)</tt>
|
||||
##### `<em>collection</em>(force_reload = false)`
|
||||
|
||||
The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
|
||||
The `<em>collection</em>` method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
|
||||
|
||||
```ruby
|
||||
@orders = @customer.orders
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em><<(object, ...)</tt>
|
||||
##### `<em>collection</em><<(object, ...)`
|
||||
|
||||
The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
|
||||
The `<em>collection</em><<` method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
|
||||
|
||||
```ruby
|
||||
@customer.orders << @order1
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em>.delete(object, ...)</tt>
|
||||
##### `<em>collection</em>.delete(object, ...)`
|
||||
|
||||
The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by setting their foreign keys to +NULL+.
|
||||
The `<em>collection</em>.delete` method removes one or more objects from the collection by setting their foreign keys to +NULL+.
|
||||
|
||||
```ruby
|
||||
@customer.orders.delete(@order1)
|
||||
|
@ -1196,29 +1196,29 @@ The <tt><em>collection</em>.delete</tt> method removes one or more objects from
|
|||
WARNING: Additionally, objects will be destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+.
|
||||
|
||||
|
||||
##### <tt><em>collection</em>=objects</tt>
|
||||
##### `<em>collection</em>=objects`
|
||||
|
||||
The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
|
||||
The `<em>collection</em>=` method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
|
||||
|
||||
##### <tt><em>collection_singular</em>_ids</tt>
|
||||
##### `<em>collection_singular</em>_ids`
|
||||
|
||||
The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.
|
||||
The `<em>collection_singular</em>_ids` method returns an array of the ids of the objects in the collection.
|
||||
|
||||
```ruby
|
||||
@order_ids = @customer.order_ids
|
||||
```
|
||||
|
||||
##### <tt><em>collection_singular</em>_ids=ids</tt>
|
||||
##### `<em>collection_singular</em>_ids=ids`
|
||||
|
||||
The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
|
||||
The `<em>collection_singular</em>_ids=` method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
|
||||
|
||||
##### <tt><em>collection</em>.clear</tt>
|
||||
##### `<em>collection</em>.clear`
|
||||
|
||||
The <tt><em>collection</em>.clear</tt> method removes every object from the collection. This destroys the associated objects if they are associated with +:dependent => :destroy+, deletes them directly from the database if +:dependent => :delete_all+, and otherwise sets their foreign keys to +NULL+.
|
||||
The `<em>collection</em>.clear` method removes every object from the collection. This destroys the associated objects if they are associated with +:dependent => :destroy+, deletes them directly from the database if +:dependent => :delete_all+, and otherwise sets their foreign keys to +NULL+.
|
||||
|
||||
##### <tt><em>collection</em>.empty?</tt>
|
||||
##### `<em>collection</em>.empty?`
|
||||
|
||||
The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects.
|
||||
The `<em>collection</em>.empty?` method returns +true+ if the collection does not contain any associated objects.
|
||||
|
||||
```ruby
|
||||
<% if @customer.orders.empty? %>
|
||||
|
@ -1226,47 +1226,47 @@ The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection
|
|||
<% end %>
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em>.size</tt>
|
||||
##### `<em>collection</em>.size`
|
||||
|
||||
The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.
|
||||
The `<em>collection</em>.size` method returns the number of objects in the collection.
|
||||
|
||||
```ruby
|
||||
@order_count = @customer.orders.size
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em>.find(...)</tt>
|
||||
##### `<em>collection</em>.find(...)`
|
||||
|
||||
The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
|
||||
The `<em>collection</em>.find` method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
|
||||
|
||||
```ruby
|
||||
@open_orders = @customer.orders.find(1)
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em>.where(...)</tt>
|
||||
##### `<em>collection</em>.where(...)`
|
||||
|
||||
The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.
|
||||
The `<em>collection</em>.where` method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.
|
||||
|
||||
```ruby
|
||||
@open_orders = @customer.orders.where(:open => true) # No query yet
|
||||
@open_order = @open_orders.first # Now the database will be queried
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em>.exists?(...)</tt>
|
||||
##### `<em>collection</em>.exists?(...)`
|
||||
|
||||
The <tt><em>collection</em>.exists?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
|
||||
The `<em>collection</em>.exists?` method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
|
||||
|
||||
##### <tt><em>collection</em>.build(attributes = {}, ...)</tt>
|
||||
##### `<em>collection</em>.build(attributes = {}, ...)`
|
||||
|
||||
The <tt><em>collection</em>.build</tt> method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
|
||||
The `<em>collection</em>.build` method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
|
||||
|
||||
```ruby
|
||||
@order = @customer.orders.build(:order_date => Time.now,
|
||||
:order_number => "A12345")
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em>.create(attributes = {})</tt>
|
||||
##### `<em>collection</em>.create(attributes = {})`
|
||||
|
||||
The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
|
||||
The `<em>collection</em>.create` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
|
||||
|
||||
```ruby
|
||||
@order = @customer.orders.create(:order_date => Time.now,
|
||||
|
@ -1551,7 +1551,7 @@ If any of these saves fails due to validation errors, then the assignment statem
|
|||
|
||||
If the parent object (the one declaring the +has_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
|
||||
|
||||
If you want to assign an object to a +has_many+ association without saving the object, use the <tt><em>collection</em>.build</tt> method.
|
||||
If you want to assign an object to a +has_many+ association without saving the object, use the `<em>collection</em>.build` method.
|
||||
|
||||
### +has_and_belongs_to_many+ Association Reference
|
||||
|
||||
|
@ -1561,22 +1561,22 @@ The +has_and_belongs_to_many+ association creates a many-to-many relationship wi
|
|||
|
||||
When you declare a +has_and_belongs_to_many+ association, the declaring class automatically gains 13 methods related to the association:
|
||||
|
||||
* <tt><em>collection</em>(force_reload = false)</tt>
|
||||
* <tt><em>collection</em><<(object, ...)</tt>
|
||||
* <tt><em>collection</em>.delete(object, ...)</tt>
|
||||
* <tt><em>collection</em>=objects</tt>
|
||||
* <tt><em>collection_singular</em>_ids</tt>
|
||||
* <tt><em>collection_singular</em>_ids=ids</tt>
|
||||
* <tt><em>collection</em>.clear</tt>
|
||||
* <tt><em>collection</em>.empty?</tt>
|
||||
* <tt><em>collection</em>.size</tt>
|
||||
* <tt><em>collection</em>.find(...)</tt>
|
||||
* <tt><em>collection</em>.where(...)</tt>
|
||||
* <tt><em>collection</em>.exists?(...)</tt>
|
||||
* <tt><em>collection</em>.build(attributes = {})</tt>
|
||||
* <tt><em>collection</em>.create(attributes = {})</tt>
|
||||
* `<em>collection</em>(force_reload = false)`
|
||||
* `<em>collection</em><<(object, ...)`
|
||||
* `<em>collection</em>.delete(object, ...)`
|
||||
* `<em>collection</em>=objects`
|
||||
* `<em>collection_singular</em>_ids`
|
||||
* `<em>collection_singular</em>_ids=ids`
|
||||
* `<em>collection</em>.clear`
|
||||
* `<em>collection</em>.empty?`
|
||||
* `<em>collection</em>.size`
|
||||
* `<em>collection</em>.find(...)`
|
||||
* `<em>collection</em>.where(...)`
|
||||
* `<em>collection</em>.exists?(...)`
|
||||
* `<em>collection</em>.build(attributes = {})`
|
||||
* `<em>collection</em>.create(attributes = {})`
|
||||
|
||||
In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_and_belongs_to_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol. For example, given the declaration:
|
||||
In all of these methods, `<em>collection</em>` is replaced with the symbol passed as the first argument to +has_and_belongs_to_many+, and `<em>collection_singular</em>` is replaced with the singularized version of that symbol. For example, given the declaration:
|
||||
|
||||
```ruby
|
||||
class Part < ActiveRecord::Base
|
||||
|
@ -1610,55 +1610,55 @@ If the join table for a +has_and_belongs_to_many+ association has additional col
|
|||
WARNING: The use of extra attributes on the join table in a +has_and_belongs_to_many+ association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a +has_many :through+ association instead of +has_and_belongs_to_many+.
|
||||
|
||||
|
||||
##### <tt><em>collection</em>(force_reload = false)</tt>
|
||||
##### `<em>collection</em>(force_reload = false)`
|
||||
|
||||
The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
|
||||
The `<em>collection</em>` method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
|
||||
|
||||
```ruby
|
||||
@assemblies = @part.assemblies
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em><<(object, ...)</tt>
|
||||
##### `<em>collection</em><<(object, ...)`
|
||||
|
||||
The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by creating records in the join table.
|
||||
The `<em>collection</em><<` method adds one or more objects to the collection by creating records in the join table.
|
||||
|
||||
```ruby
|
||||
@part.assemblies << @assembly1
|
||||
```
|
||||
|
||||
NOTE: This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>.
|
||||
NOTE: This method is aliased as `<em>collection</em>.concat` and `<em>collection</em>.push`.
|
||||
|
||||
##### <tt><em>collection</em>.delete(object, ...)</tt>
|
||||
##### `<em>collection</em>.delete(object, ...)`
|
||||
|
||||
The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
|
||||
The `<em>collection</em>.delete` method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
|
||||
|
||||
```ruby
|
||||
@part.assemblies.delete(@assembly1)
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em>=objects</tt>
|
||||
##### `<em>collection</em>=objects`
|
||||
|
||||
The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
|
||||
The `<em>collection</em>=` method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
|
||||
|
||||
##### <tt><em>collection_singular</em>_ids</tt>
|
||||
##### `<em>collection_singular</em>_ids`
|
||||
|
||||
The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.
|
||||
The `<em>collection_singular</em>_ids` method returns an array of the ids of the objects in the collection.
|
||||
|
||||
```ruby
|
||||
@assembly_ids = @part.assembly_ids
|
||||
```
|
||||
|
||||
##### <tt><em>collection_singular</em>_ids=ids</tt>
|
||||
##### `<em>collection_singular</em>_ids=ids`
|
||||
|
||||
The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
|
||||
The `<em>collection_singular</em>_ids=` method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
|
||||
|
||||
##### <tt><em>collection</em>.clear</tt>
|
||||
##### `<em>collection</em>.clear`
|
||||
|
||||
The <tt><em>collection</em>.clear</tt> method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.
|
||||
The `<em>collection</em>.clear` method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.
|
||||
|
||||
##### <tt><em>collection</em>.empty?</tt>
|
||||
##### `<em>collection</em>.empty?`
|
||||
|
||||
The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects.
|
||||
The `<em>collection</em>.empty?` method returns +true+ if the collection does not contain any associated objects.
|
||||
|
||||
```ruby
|
||||
<% if @part.assemblies.empty? %>
|
||||
|
@ -1666,46 +1666,46 @@ The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection
|
|||
<% end %>
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em>.size</tt>
|
||||
##### `<em>collection</em>.size`
|
||||
|
||||
The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.
|
||||
The `<em>collection</em>.size` method returns the number of objects in the collection.
|
||||
|
||||
```ruby
|
||||
@assembly_count = @part.assemblies.size
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em>.find(...)</tt>
|
||||
##### `<em>collection</em>.find(...)`
|
||||
|
||||
The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection.
|
||||
The `<em>collection</em>.find` method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection.
|
||||
|
||||
```ruby
|
||||
@assembly = @part.assemblies.find(1)
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em>.where(...)</tt>
|
||||
##### `<em>collection</em>.where(...)`
|
||||
|
||||
The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. It also adds the additional condition that the object must be in the collection.
|
||||
The `<em>collection</em>.where` method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. It also adds the additional condition that the object must be in the collection.
|
||||
|
||||
```ruby
|
||||
@new_assemblies = @part.assemblies.where("created_at > ?", 2.days.ago)
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em>.exists?(...)</tt>
|
||||
##### `<em>collection</em>.exists?(...)`
|
||||
|
||||
The <tt><em>collection</em>.exists?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
|
||||
The `<em>collection</em>.exists?` method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
|
||||
|
||||
##### <tt><em>collection</em>.build(attributes = {})</tt>
|
||||
##### `<em>collection</em>.build(attributes = {})`
|
||||
|
||||
The <tt><em>collection</em>.build</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will _not_ yet be saved.
|
||||
The `<em>collection</em>.build` method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will _not_ yet be saved.
|
||||
|
||||
```ruby
|
||||
@assembly = @part.assemblies.build(
|
||||
{:assembly_name => "Transmission housing"})
|
||||
```
|
||||
|
||||
##### <tt><em>collection</em>.create(attributes = {})</tt>
|
||||
##### `<em>collection</em>.create(attributes = {})`
|
||||
|
||||
The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through the join table will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
|
||||
The `<em>collection</em>.create` method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through the join table will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
|
||||
|
||||
```ruby
|
||||
@assembly = @part.assemblies.create(
|
||||
|
@ -1889,7 +1889,7 @@ If any of these saves fails due to validation errors, then the assignment statem
|
|||
|
||||
If the parent object (the one declaring the +has_and_belongs_to_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
|
||||
|
||||
If you want to assign an object to a +has_and_belongs_to_many+ association without saving the object, use the <tt><em>collection</em>.build</tt> method.
|
||||
If you want to assign an object to a +has_and_belongs_to_many+ association without saving the object, use the `<em>collection</em>.build` method.
|
||||
|
||||
### Association Callbacks
|
||||
|
||||
|
|
|
@ -20,12 +20,12 @@ Command Line Basics
|
|||
|
||||
There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:
|
||||
|
||||
* <tt>rails console</tt>
|
||||
* <tt>rails server</tt>
|
||||
* <tt>rake</tt>
|
||||
* <tt>rails generate</tt>
|
||||
* <tt>rails dbconsole</tt>
|
||||
* <tt>rails new app_name</tt>
|
||||
* `rails console`
|
||||
* `rails server`
|
||||
* `rake`
|
||||
* `rails generate`
|
||||
* `rails dbconsole`
|
||||
* `rails new app_name`
|
||||
|
||||
Let's create a simple Rails application to step through each of these commands in context.
|
||||
|
||||
|
@ -74,7 +74,7 @@ $ rails server
|
|||
|
||||
With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open "http://localhost:3000":http://localhost:3000, you will see a basic Rails app running.
|
||||
|
||||
INFO: You can also use the alias "s" to start the server: <tt>rails s</tt>.
|
||||
INFO: You can also use the alias "s" to start the server: `rails s`.
|
||||
|
||||
The server can be run on a different port using the +-p+ option. The default development environment can be changed using +-e+.
|
||||
|
||||
|
@ -88,7 +88,7 @@ The +-b+ option binds Rails to the specified ip, by default it is 0.0.0.0. You c
|
|||
|
||||
The +rails generate+ command uses templates to create a whole lot of things. Running +rails generate+ by itself gives a list of available generators:
|
||||
|
||||
INFO: You can also use the alias "g" to invoke the generator command: <tt>rails g</tt>.
|
||||
INFO: You can also use the alias "g" to invoke the generator command: `rails g`.
|
||||
|
||||
```shell
|
||||
$ rails generate
|
||||
|
@ -276,7 +276,7 @@ Go to your browser and open "http://localhost:3000/high_scores":http://localhost
|
|||
|
||||
The +console+ command lets you interact with your Rails application from the command line. On the underside, +rails console+ uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.
|
||||
|
||||
INFO: You can also use the alias "c" to invoke the console: <tt>rails c</tt>.
|
||||
INFO: You can also use the alias "c" to invoke the console: `rails c`.
|
||||
|
||||
You can specify the environment in which the +console+ command should operate.
|
||||
|
||||
|
@ -297,17 +297,17 @@ irb(main):001:0>
|
|||
|
||||
+rails dbconsole+ figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3.
|
||||
|
||||
INFO: You can also use the alias "db" to invoke the dbconsole: <tt>rails db</tt>.
|
||||
INFO: You can also use the alias "db" to invoke the dbconsole: `rails db`.
|
||||
|
||||
### +rails runner+
|
||||
|
||||
<tt>runner</tt> runs Ruby code in the context of Rails non-interactively. For instance:
|
||||
`runner` runs Ruby code in the context of Rails non-interactively. For instance:
|
||||
|
||||
```shell
|
||||
$ rails runner "Model.long_running_method"
|
||||
```
|
||||
|
||||
INFO: You can also use the alias "r" to invoke the runner: <tt>rails r</tt>.
|
||||
INFO: You can also use the alias "r" to invoke the runner: `rails r`.
|
||||
|
||||
You can specify the environment in which the +runner+ command should operate using the +-e+ switch.
|
||||
|
||||
|
@ -319,7 +319,7 @@ $ rails runner -e staging "Model.long_running_method"
|
|||
|
||||
Think of +destroy+ as the opposite of +generate+. It'll figure out what generate did, and undo it.
|
||||
|
||||
INFO: You can also use the alias "d" to invoke the destroy command: <tt>rails d</tt>.
|
||||
INFO: You can also use the alias "d" to invoke the destroy command: `rails d`.
|
||||
|
||||
```shell
|
||||
$ rails generate model Oops
|
||||
|
@ -363,7 +363,7 @@ rake tmp:create # Creates tmp directories for sessions, cache, sockets,
|
|||
|
||||
### +about+
|
||||
|
||||
<tt>rake about</tt> gives information about version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version. It is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.
|
||||
`rake about` gives information about version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version. It is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.
|
||||
|
||||
```shell
|
||||
$ rake about
|
||||
|
@ -386,7 +386,7 @@ Database schema version 20110805173523
|
|||
|
||||
### +assets+
|
||||
|
||||
You can precompile the assets in <tt>app/assets</tt> using <tt>rake assets:precompile</tt> and remove those compiled assets using <tt>rake assets:clean</tt>.
|
||||
You can precompile the assets in `app/assets` using `rake assets:precompile` and remove those compiled assets using `rake assets:clean`.
|
||||
|
||||
### +db+
|
||||
|
||||
|
@ -461,24 +461,24 @@ rspec/model/user_spec.rb:
|
|||
|
||||
INFO: A good description of unit testing in Rails is given in "A Guide to Testing Rails Applications":testing.html
|
||||
|
||||
Rails comes with a test suite called <tt>Test::Unit</tt>. Rails owes its stability to the use of tests. The tasks available in the +test:+ namespace helps in running the different tests you will hopefully write.
|
||||
Rails comes with a test suite called `Test::Unit`. Rails owes its stability to the use of tests. The tasks available in the +test:+ namespace helps in running the different tests you will hopefully write.
|
||||
|
||||
### +tmp+
|
||||
|
||||
The <tt>Rails.root/tmp</tt> directory is, like the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions.
|
||||
The `Rails.root/tmp` directory is, like the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions.
|
||||
|
||||
The +tmp:+ namespaced tasks will help you clear the <tt>Rails.root/tmp</tt> directory:
|
||||
The +tmp:+ namespaced tasks will help you clear the `Rails.root/tmp` directory:
|
||||
|
||||
* +rake tmp:cache:clear+ clears <tt>tmp/cache</tt>.
|
||||
* +rake tmp:sessions:clear+ clears <tt>tmp/sessions</tt>.
|
||||
* +rake tmp:sockets:clear+ clears <tt>tmp/sockets</tt>.
|
||||
* +rake tmp:cache:clear+ clears `tmp/cache`.
|
||||
* +rake tmp:sessions:clear+ clears `tmp/sessions`.
|
||||
* +rake tmp:sockets:clear+ clears `tmp/sockets`.
|
||||
* +rake tmp:clear+ clears all the three: cache, sessions and sockets.
|
||||
|
||||
### Miscellaneous
|
||||
|
||||
* +rake stats+ is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
|
||||
* +rake secret+ will give you a pseudo-random key to use for your session secret.
|
||||
* <tt>rake time:zones:all</tt> lists all the timezones Rails knows about.
|
||||
* `rake time:zones:all` lists all the timezones Rails knows about.
|
||||
|
||||
### Writing Rake Tasks
|
||||
|
||||
|
@ -486,7 +486,7 @@ If you have (or want to write) any automation scripts outside your app (data imp
|
|||
|
||||
INFO: "Complete guide about how to write tasks":http://rake.rubyforge.org/files/doc/rakefile_rdoc.html is available in the official documentation.
|
||||
|
||||
Tasks should be placed in <tt>Rails.root/lib/tasks</tt> and should have a +.rake+ extension.
|
||||
Tasks should be placed in `Rails.root/lib/tasks` and should have a +.rake+ extension.
|
||||
|
||||
Each task should be defined in next format (dependencies are optional):
|
||||
|
||||
|
@ -517,7 +517,7 @@ namespace :do
|
|||
end
|
||||
```
|
||||
|
||||
You can see your tasks to be listed by <tt>rake -T</tt> command. And, according to the examples above, you can invoke them as follows:
|
||||
You can see your tasks to be listed by `rake -T` command. And, according to the examples above, you can invoke them as follows:
|
||||
|
||||
```shell
|
||||
rake task_name
|
||||
|
|
|
@ -260,7 +260,7 @@ config.middleware.delete ActionDispatch::BestStandardsSupport
|
|||
|
||||
### Configuring Active Record
|
||||
|
||||
<tt>config.active_record</tt> includes a variety of configuration options:
|
||||
`config.active_record` includes a variety of configuration options:
|
||||
|
||||
* +config.active_record.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then passed on to any new database connections made. You can retrieve this logger by calling +logger+ on either an Active Record model class or an Active Record model instance. Set to +nil+ to disable logging.
|
||||
|
||||
|
@ -298,13 +298,13 @@ The schema dumper adds one additional configuration option:
|
|||
|
||||
### Configuring Action Controller
|
||||
|
||||
<tt>config.action_controller</tt> includes a number of configuration settings:
|
||||
`config.action_controller` includes a number of configuration settings:
|
||||
|
||||
* +config.action_controller.asset_host+ sets the host for the assets. Useful when CDNs are used for hosting assets rather than the application server itself.
|
||||
|
||||
* +config.action_controller.asset_path+ takes a block which configures where assets can be found. Shorter version of +config.action_controller.asset_path+.
|
||||
|
||||
* +config.action_controller.page_cache_directory+ should be the document root for the web server and is set using <tt>Base.page_cache_directory = "/document/root"</tt>. For Rails, this directory has already been set to +Rails.public_path+ (which is usually set to <tt>Rails.root + "/public"</tt>). Changing this setting can be useful to avoid naming conflicts with files in <tt>public/</tt>, but doing so will likely require configuring your web server to look in the new location for cached files.
|
||||
* +config.action_controller.page_cache_directory+ should be the document root for the web server and is set using `Base.page_cache_directory = "/document/root"`. For Rails, this directory has already been set to +Rails.public_path+ (which is usually set to `Rails.root + "/public"`). Changing this setting can be useful to avoid naming conflicts with files in `public/`, but doing so will likely require configuring your web server to look in the new location for cached files.
|
||||
|
||||
* +config.action_controller.page_cache_extension+ configures the extension used for cached pages saved to +page_cache_directory+. Defaults to +.html+.
|
||||
|
||||
|
@ -322,7 +322,7 @@ The schema dumper adds one additional configuration option:
|
|||
|
||||
The caching code adds two additional settings:
|
||||
|
||||
* +ActionController::Base.page_cache_directory+ sets the directory where Rails will create cached pages for your web server. The default is +Rails.public_path+ (which is usually set to <tt>Rails.root + "/public"</tt>).
|
||||
* +ActionController::Base.page_cache_directory+ sets the directory where Rails will create cached pages for your web server. The default is +Rails.public_path+ (which is usually set to `Rails.root + "/public"`).
|
||||
|
||||
* +ActionController::Base.page_cache_extension+ sets the extension to be used when generating pages for the cache (this is ignored if the incoming request already has an extension). The default is +.html+.
|
||||
|
||||
|
@ -346,7 +346,7 @@ config.action_dispatch.default_headers = { 'X-Frame-Options' => 'SAMEORIGIN', 'X
|
|||
|
||||
### Configuring Action View
|
||||
|
||||
<tt>config.action_view</tt> includes a small number of configuration settings:
|
||||
`config.action_view` includes a small number of configuration settings:
|
||||
|
||||
* +config.action_view.field_error_proc+ provides an HTML generator for displaying errors that come from Active Record. The default is
|
||||
|
||||
|
@ -473,13 +473,13 @@ Just about every Rails application will interact with a database. The database t
|
|||
* The +test+ environment is used when running automated tests.
|
||||
* The +production+ environment is used when you deploy your application for the world to use.
|
||||
|
||||
TIP: You don't have to update the database configurations manually. If you look at the options of the application generator, you will see that one of the options is named <tt>--database</tt>. This option allows you to choose an adapter from a list of the most used relational databases. You can even run the generator repeatedly: <tt>cd .. && rails new blog --database=mysql</tt>. When you confirm the overwriting of the +config/database.yml+ file, your application will be configured for MySQL instead of SQLite. Detailed examples of the common database connections are below.
|
||||
TIP: You don't have to update the database configurations manually. If you look at the options of the application generator, you will see that one of the options is named `--database`. This option allows you to choose an adapter from a list of the most used relational databases. You can even run the generator repeatedly: `cd .. && rails new blog --database=mysql`. When you confirm the overwriting of the +config/database.yml+ file, your application will be configured for MySQL instead of SQLite. Detailed examples of the common database connections are below.
|
||||
|
||||
#### Configuring an SQLite3 Database
|
||||
|
||||
Rails comes with built-in support for "SQLite3":http://www.sqlite.org, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using an SQLite database when creating a new project, but you can always change it later.
|
||||
|
||||
Here's the section of the default configuration file (<tt>config/database.yml</tt>) with connection information for the development environment:
|
||||
Here's the section of the default configuration file (`config/database.yml`) with connection information for the development environment:
|
||||
|
||||
```yaml
|
||||
development:
|
||||
|
|
|
@ -476,7 +476,7 @@ Now you should know where you are in the running trace and be able to print the
|
|||
|
||||
Use +step+ (abbreviated +s+) to continue running your program until the next logical stopping point and return control to the debugger.
|
||||
|
||||
TIP: You can also use <tt>step<plus> n</tt> and <tt>step- n</tt> to move forward or backward +n+ steps respectively.
|
||||
TIP: You can also use `step<plus> n` and `step- n` to move forward or backward +n+ steps respectively.
|
||||
|
||||
You may also use +next+ which is similar to step, but function or method calls that appear within the line of code are executed without stopping. As with step, you may use plus sign to move _n_ steps.
|
||||
|
||||
|
|
|
@ -553,14 +553,14 @@ Now instead of the ugly Ruby object output the author's name will be displayed.
|
|||
|
||||
#### Using a controller provided by the application
|
||||
|
||||
Because Rails controllers generally share code for things like authentication and accessing session variables, by default they inherit from <tt>ApplicationController</tt>. Rails engines, however are scoped to run independently from the main application, so each engine gets a scoped +ApplicationController+. This namespace prevents code collisions, but often engine controllers should access methods in the main application's +ApplicationController+. An easy way to provide this access is to change the engine's scoped +ApplicationController+ to inherit from the main application's +ApplicationController+. For our Blorgh engine this would be done by changing +app/controllers/blorgh/application_controller.rb+ to look like:
|
||||
Because Rails controllers generally share code for things like authentication and accessing session variables, by default they inherit from `ApplicationController`. Rails engines, however are scoped to run independently from the main application, so each engine gets a scoped +ApplicationController+. This namespace prevents code collisions, but often engine controllers should access methods in the main application's +ApplicationController+. An easy way to provide this access is to change the engine's scoped +ApplicationController+ to inherit from the main application's +ApplicationController+. For our Blorgh engine this would be done by changing +app/controllers/blorgh/application_controller.rb+ to look like:
|
||||
|
||||
```ruby
|
||||
class Blorgh::ApplicationController < ApplicationController
|
||||
end
|
||||
```
|
||||
|
||||
By default, the engine's controllers inherit from <tt>Blorgh::ApplicationController</tt>. So, after making this change they will have access to the main applications +ApplicationController+ as though they were part of the main application.
|
||||
By default, the engine's controllers inherit from `Blorgh::ApplicationController`. So, after making this change they will have access to the main applications +ApplicationController+ as though they were part of the main application.
|
||||
|
||||
This change does require that the engine is run from a Rails application that has an +ApplicationController+.
|
||||
|
||||
|
|
|
@ -458,7 +458,7 @@ As with other helpers, if you were to use the +select+ helper on a form builder
|
|||
<%= f.select(:city_id, ...) %>
|
||||
```
|
||||
|
||||
WARNING: If you are using +select+ (or similar helpers such as +collection_select+, +select_tag+) to set a +belongs_to+ association you must pass the name of the foreign key (in the example above +city_id+), not the name of association itself. If you specify +city+ instead of +city_id+ Active Record will raise an error along the lines of <tt> ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750) </tt> when you pass the +params+ hash to +Person.new+ or +update_attributes+. Another way of looking at this is that form helpers only edit attributes. You should also be aware of the potential security ramifications of allowing users to edit foreign keys directly. You may wish to consider the use of +attr_protected+ and +attr_accessible+. For further details on this, see the "Ruby On Rails Security Guide":security.html#mass-assignment.
|
||||
WARNING: If you are using +select+ (or similar helpers such as +collection_select+, +select_tag+) to set a +belongs_to+ association you must pass the name of the foreign key (in the example above +city_id+), not the name of association itself. If you specify +city+ instead of +city_id+ Active Record will raise an error along the lines of ` ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750) ` when you pass the +params+ hash to +Person.new+ or +update_attributes+. Another way of looking at this is that form helpers only edit attributes. You should also be aware of the potential security ramifications of allowing users to edit foreign keys directly. You may wish to consider the use of +attr_protected+ and +attr_accessible+. For further details on this, see the "Ruby On Rails Security Guide":security.html#mass-assignment.
|
||||
|
||||
### Option Tags from a Collection of Arbitrary Objects
|
||||
|
||||
|
@ -594,7 +594,7 @@ The following two forms both upload a file.
|
|||
<% end %>
|
||||
```
|
||||
|
||||
NOTE: Since Rails 3.1, forms rendered using +form_for+ have their encoding set to <tt>multipart/form-data</tt> automatically once a +file_field+ is used inside the block. Previous versions required you to set this explicitly.
|
||||
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]+.
|
||||
|
||||
|
@ -617,7 +617,7 @@ NOTE: If the user has not selected a file the corresponding parameter will be an
|
|||
|
||||
### Dealing with Ajax
|
||||
|
||||
Unlike other forms making an asynchronous file upload form is not as simple as providing +form_for+ with <tt>:remote => true</tt>. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.
|
||||
Unlike other forms making an asynchronous file upload form is not as simple as providing +form_for+ with `:remote => true`. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.
|
||||
|
||||
Customizing Form Builders
|
||||
-------------------------
|
||||
|
|
|
@ -211,7 +211,7 @@ Now that we have made the controller and view, we need to tell Rails when we wan
|
|||
|
||||
To fix this, delete the +index.html+ file located inside the +public+ directory of the application.
|
||||
|
||||
You need to do this because Rails will serve any static file in the +public+ directory that matches a route in preference to any dynamic content you generate from the controllers. The +index.html+ file is special: it will be served if a request comes in at the root route, e.g. http://localhost:3000. If another request such as http://localhost:3000/welcome happened, a static file at <tt>public/welcome.html</tt> would be served first, but only if it existed.
|
||||
You need to do this because Rails will serve any static file in the +public+ directory that matches a route in preference to any dynamic content you generate from the controllers. The +index.html+ file is special: it will be served if a request comes in at the root route, e.g. http://localhost:3000. If another request such as http://localhost:3000/welcome happened, a static file at `public/welcome.html` would be served first, but only if it existed.
|
||||
|
||||
Next, you have to tell Rails where your actual home page is located.
|
||||
|
||||
|
@ -1559,7 +1559,7 @@ following:
|
|||
|
||||
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+
|
||||
method iterates over the <tt>@post.comments</tt> collection, it assigns each
|
||||
method iterates over the `@post.comments` collection, it assigns each
|
||||
comment to a local variable named the same as the partial, in this case
|
||||
+comment+ which is then available in the partial for us to show.
|
||||
|
||||
|
@ -1605,9 +1605,9 @@ Then you make the +app/views/posts/show.html.erb+ look like the following:
|
|||
```
|
||||
|
||||
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
|
||||
string and realize that you want to render the <tt>_form.html.erb</tt> file in
|
||||
the <tt>app/views/comments</tt> directory.
|
||||
`comments/form`. Rails is smart enough to spot the forward slash in that
|
||||
string and realize that you want to render the `_form.html.erb` file in
|
||||
the `app/views/comments` directory.
|
||||
|
||||
The +@post+ object is available to any partials rendered in the view because we
|
||||
defined it as an instance variable.
|
||||
|
@ -1640,8 +1640,8 @@ So first, let's add the delete link in the
|
|||
</p>
|
||||
```
|
||||
|
||||
Clicking this new "Destroy Comment" link will fire off a <tt>DELETE
|
||||
/posts/:id/comments/:id</tt> to our +CommentsController+, which can then use
|
||||
Clicking this new "Destroy Comment" link will fire off a `DELETE
|
||||
/posts/:id/comments/:id` 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:
|
||||
|
||||
|
@ -1665,7 +1665,7 @@ end
|
|||
```
|
||||
|
||||
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
|
||||
within the `@post.comments` collection, and then remove it from the
|
||||
database and send us back to the show action for the post.
|
||||
|
||||
|
||||
|
@ -1695,7 +1695,7 @@ this situation.
|
|||
|
||||
In the +PostsController+ we need to have a way to block access to the various
|
||||
actions if the person is not authenticated, here we can use the Rails
|
||||
<tt>http_basic_authenticate_with</tt> method, allowing access to the requested
|
||||
`http_basic_authenticate_with` method, allowing access to the requested
|
||||
action if that method allows it.
|
||||
|
||||
To use the authentication system, we specify it at the top of our
|
||||
|
|
|
@ -220,7 +220,7 @@ command = aliases[command] || command
|
|||
TIP: As you can see, an empty ARGV list will make Rails show the help
|
||||
snippet.
|
||||
|
||||
If we used <tt>s</tt> rather than +server+, Rails will use the +aliases+ defined in the file and match them to their respective commands. With the +server+ command, Rails will run this code:
|
||||
If we used `s` rather than +server+, Rails will use the +aliases+ defined in the file and match them to their respective commands. With the +server+ command, Rails will run this code:
|
||||
|
||||
```ruby
|
||||
when 'server'
|
||||
|
|
|
@ -728,7 +728,7 @@ These two files for jQuery, +jquery.js+ and +jquery_ujs.js+ must be placed insid
|
|||
|
||||
WARNING: If you are using the asset pipeline, this tag will render a +script+ tag for an asset called +defaults.js+, which would not exist in your application unless you've explicitly created it.
|
||||
|
||||
And you can in any case override the +:defaults+ expansion in <tt>config/application.rb</tt>:
|
||||
And you can in any case override the +:defaults+ expansion in `config/application.rb`:
|
||||
|
||||
```ruby
|
||||
config.action_view.javascript_expansions[:defaults] = %w(foo.js bar.js)
|
||||
|
@ -746,7 +746,7 @@ And use them by referencing them exactly like +:defaults+:
|
|||
<%= javascript_include_tag :projects %>
|
||||
```
|
||||
|
||||
When using <tt>:defaults</tt>, if an <tt>application.js</tt> file exists in <tt>public/javascripts</tt> it will be included as well at the end.
|
||||
When using `:defaults`, if an `application.js` file exists in `public/javascripts` it will be included as well at the end.
|
||||
|
||||
Also, if the asset pipeline is disabled, the +:all+ expansion loads every JavaScript file in +public/javascripts+:
|
||||
|
||||
|
|
|
@ -85,7 +85,7 @@ existing users.
|
|||
|
||||
### Using the change method
|
||||
|
||||
Rails 3.1 makes migrations smarter by providing a new <tt>change</tt> method.
|
||||
Rails 3.1 makes migrations smarter by providing a new `change` 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
|
||||
the migration is rolled back without the need to write a separate +down+ method.
|
||||
|
@ -105,7 +105,7 @@ end
|
|||
|
||||
### Migrations are Classes
|
||||
|
||||
A migration is a subclass of <tt>ActiveRecord::Migration</tt> that implements
|
||||
A migration is a subclass of `ActiveRecord::Migration` that implements
|
||||
two methods: +up+ (perform the required transformations) and +down+ (revert
|
||||
them).
|
||||
|
||||
|
@ -546,12 +546,12 @@ method to execute arbitrary SQL.
|
|||
|
||||
For more details and examples of individual methods, check the API documentation.
|
||||
In particular the documentation for
|
||||
"<tt>ActiveRecord::ConnectionAdapters::SchemaStatements</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html
|
||||
"`ActiveRecord::ConnectionAdapters::SchemaStatements`":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html
|
||||
(which provides the methods available in the +up+ and +down+ methods),
|
||||
"<tt>ActiveRecord::ConnectionAdapters::TableDefinition</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html
|
||||
"`ActiveRecord::ConnectionAdapters::TableDefinition`":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html
|
||||
(which provides the methods available on the object yielded by +create_table+)
|
||||
and
|
||||
"<tt>ActiveRecord::ConnectionAdapters::Table</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html
|
||||
"`ActiveRecord::ConnectionAdapters::Table`":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html
|
||||
(which provides the methods available on the object yielded by +change_table+).
|
||||
|
||||
### When to Use the +change+ Method
|
||||
|
|
|
@ -387,7 +387,7 @@ Run +rake+ one final time and you should see:
|
|||
7 tests, 7 assertions, 0 failures, 0 errors, 0 skips
|
||||
```
|
||||
|
||||
NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use <tt>send("#{self.class.yaffle_text_field}=", string.to_squawk)</tt>.
|
||||
NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use `send("#{self.class.yaffle_text_field}=", string.to_squawk)`.
|
||||
|
||||
Generators
|
||||
----------
|
||||
|
|
|
@ -26,11 +26,11 @@ Rails on Rack
|
|||
|
||||
### Rails Application's Rack Object
|
||||
|
||||
<tt>ApplicationName::Application</tt> is the primary Rack application object of a Rails application. Any Rack compliant web server should be using +ApplicationName::Application+ object to serve a Rails application.
|
||||
`ApplicationName::Application` is the primary Rack application object of a Rails application. Any Rack compliant web server should be using +ApplicationName::Application+ object to serve a Rails application.
|
||||
|
||||
### +rails server+
|
||||
|
||||
<tt>rails server</tt> does the basic job of creating a +Rack::Server+ object and starting the webserver.
|
||||
`rails server` does the basic job of creating a +Rack::Server+ object and starting the webserver.
|
||||
|
||||
Here's how +rails server+ creates an instance of +Rack::Server+
|
||||
|
||||
|
@ -142,17 +142,17 @@ Purpose of each of this middlewares is explained in the "Internal Middlewares":#
|
|||
|
||||
### Configuring Middleware Stack
|
||||
|
||||
Rails provides a simple configuration interface +config.middleware+ for adding, removing and modifying the middlewares in the middleware stack via +application.rb+ or the environment specific configuration file <tt>environments/<environment>.rb</tt>.
|
||||
Rails provides a simple configuration interface +config.middleware+ for adding, removing and modifying the middlewares in the middleware stack via +application.rb+ or the environment specific configuration file `environments/<environment>.rb`.
|
||||
|
||||
#### Adding a Middleware
|
||||
|
||||
You can add a new middleware to the middleware stack using any of the following methods:
|
||||
|
||||
* <tt>config.middleware.use(new_middleware, args)</tt> - Adds the new middleware at the bottom of the middleware stack.
|
||||
* `config.middleware.use(new_middleware, args)` - Adds the new middleware at the bottom of the middleware stack.
|
||||
|
||||
* <tt>config.middleware.insert_before(existing_middleware, new_middleware, args)</tt> - Adds the new middleware before the specified existing middleware in the middleware stack.
|
||||
* `config.middleware.insert_before(existing_middleware, new_middleware, args)` - Adds the new middleware before the specified existing middleware in the middleware stack.
|
||||
|
||||
* <tt>config.middleware.insert_after(existing_middleware, new_middleware, args)</tt> - Adds the new middleware after the specified existing middleware in the middleware stack.
|
||||
* `config.middleware.insert_after(existing_middleware, new_middleware, args)` - Adds the new middleware after the specified existing middleware in the middleware stack.
|
||||
|
||||
```ruby
|
||||
# config/application.rb
|
||||
|
@ -178,7 +178,7 @@ config.middleware.swap ActionDispatch::ShowExceptions, Lifo::ShowExceptions
|
|||
|
||||
#### Middleware Stack is an Enumerable
|
||||
|
||||
The middleware stack behaves just like a normal +Enumerable+. You can use any +Enumerable+ methods to manipulate or interrogate the stack. The middleware stack also implements some +Array+ methods including <tt>[]</tt>, +unshift+ and +delete+. Methods described in the section above are just convenience methods.
|
||||
The middleware stack behaves just like a normal +Enumerable+. You can use any +Enumerable+ methods to manipulate or interrogate the stack. The middleware stack also implements some +Array+ methods including `[]`, +unshift+ and +delete+. Methods described in the section above are just convenience methods.
|
||||
|
||||
Append following lines to your application configuration:
|
||||
|
||||
|
@ -221,10 +221,10 @@ config.middleware.delete "Rack::MethodOverride"
|
|||
Much of Action Controller's functionality is implemented as Middlewares. The following list explains the purpose of each of them:
|
||||
|
||||
*+ActionDispatch::Static+*
|
||||
* Used to serve static assets. Disabled if <tt>config.serve_static_assets</tt> is true.
|
||||
* Used to serve static assets. Disabled if `config.serve_static_assets` is true.
|
||||
|
||||
*+Rack::Lock+*
|
||||
* Sets <tt>env["rack.multithread"]</tt> flag to +true+ and wraps the application within a Mutex.
|
||||
* Sets `env["rack.multithread"]` flag to +true+ and wraps the application within a Mutex.
|
||||
|
||||
*+ActiveSupport::Cache::Strategy::LocalCache::Middleware+*
|
||||
* Used for memory caching. This cache is not thread safe.
|
||||
|
@ -233,10 +233,10 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol
|
|||
* Sets an X-Runtime header, containing the time (in seconds) taken to execute the request.
|
||||
|
||||
*+Rack::MethodOverride+*
|
||||
* Allows the method to be overridden if <tt>params[:_method]</tt> is set. This is the middleware which supports the PUT and DELETE HTTP method types.
|
||||
* Allows the method to be overridden if `params[:_method]` is set. This is the middleware which supports the PUT and DELETE HTTP method types.
|
||||
|
||||
*+ActionDispatch::RequestId+*
|
||||
* Makes a unique +X-Request-Id+ header available to the response and enables the <tt>ActionDispatch::Request#uuid</tt> method.
|
||||
* Makes a unique +X-Request-Id+ header available to the response and enables the `ActionDispatch::Request#uuid` method.
|
||||
|
||||
*+Rails::Rack::Logger+*
|
||||
* Notifies the logs that the request has began. After request is complete, flushes all the logs.
|
||||
|
@ -257,7 +257,7 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol
|
|||
* Runs the prepare callbacks before serving the request.
|
||||
|
||||
*+ActiveRecord::ConnectionAdapters::ConnectionManagement+*
|
||||
* Cleans active connections after each request, unless the <tt>rack.test</tt> key in the request environment is set to +true+.
|
||||
* Cleans active connections after each request, unless the `rack.test` key in the request environment is set to +true+.
|
||||
|
||||
*+ActiveRecord::QueryCache+*
|
||||
* Enables the Active Record query cache.
|
||||
|
@ -269,10 +269,10 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol
|
|||
* Responsible for storing the session in cookies.
|
||||
|
||||
*+ActionDispatch::Flash+*
|
||||
* Sets up the flash keys. Only available if <tt>config.action_controller.session_store</tt> is set to a value.
|
||||
* Sets up the flash keys. Only available if `config.action_controller.session_store` is set to a value.
|
||||
|
||||
*+ActionDispatch::ParamsParser+*
|
||||
* Parses out parameters from the request into <tt>params</tt>.
|
||||
* Parses out parameters from the request into `params`.
|
||||
|
||||
*+ActionDispatch::Head+*
|
||||
* Converts HEAD requests to +GET+ requests and serves them as so.
|
||||
|
|
|
@ -4,7 +4,7 @@ Rails Routing from the Outside In
|
|||
This guide covers the user-facing features of Rails routing. By referring to this guide, you will be able to:
|
||||
|
||||
* Understand the code in +routes.rb+
|
||||
* Construct your own routes, using either the preferred resourceful style or the <tt>match</tt> method
|
||||
* Construct your own routes, using either the preferred resourceful style or the `match` method
|
||||
* Identify what parameters to expect an action to receive
|
||||
* Automatically create paths and URLs using route helpers
|
||||
* Use advanced techniques such as constraints and Rack endpoints
|
||||
|
@ -30,7 +30,7 @@ it asks the router to match it to a controller action. If the first matching rou
|
|||
get "/patients/:id" => "patients#show"
|
||||
```
|
||||
|
||||
the request is dispatched to the +patients+ controller's +show+ action with <tt>{ :id => "17" }</tt> in +params+.
|
||||
the request is dispatched to the +patients+ controller's +show+ action with `{ :id => "17" }` in +params+.
|
||||
|
||||
### Generating Paths and URLs from Code
|
||||
|
||||
|
@ -73,7 +73,7 @@ it asks the router to map it to a controller action. If the first matching route
|
|||
resources :photos
|
||||
```
|
||||
|
||||
Rails would dispatch that request to the +destroy+ method on the +photos+ controller with <tt>{ :id => "17" }</tt> in +params+.
|
||||
Rails would dispatch that request to the +destroy+ method on the +photos+ controller with `{ :id => "17" }` in +params+.
|
||||
|
||||
### CRUD, Verbs, and Actions
|
||||
|
||||
|
@ -445,7 +445,7 @@ You can specify static segments when creating a route:
|
|||
get ':controller/:action/:id/with_user/:user_id'
|
||||
```
|
||||
|
||||
This route would respond to paths such as +/photos/show/1/with_user/2+. In this case, +params+ would be <tt>{ :controller => "photos", :action => "show", :id => "1", :user_id => "2" }</tt>.
|
||||
This route would respond to paths such as +/photos/show/1/with_user/2+. In this case, +params+ would be `{ :controller => "photos", :action => "show", :id => "1", :user_id => "2" }`.
|
||||
|
||||
### The Query String
|
||||
|
||||
|
@ -455,7 +455,7 @@ The +params+ will also include any parameters from the query string. For example
|
|||
get ':controller/:action/:id'
|
||||
```
|
||||
|
||||
An incoming path of +/photos/show/1?user_id=2+ will be dispatched to the +show+ action of the +Photos+ controller. +params+ will be <tt>{ :controller => "photos", :action => "show", :id => "1", :user_id => "2" }</tt>.
|
||||
An incoming path of +/photos/show/1?user_id=2+ will be dispatched to the +show+ action of the +Photos+ controller. +params+ will be `{ :controller => "photos", :action => "show", :id => "1", :user_id => "2" }`.
|
||||
|
||||
### Defining Defaults
|
||||
|
||||
|
@ -667,7 +667,7 @@ Instead of a String, like +"posts#index"+, which corresponds to the +index+ acti
|
|||
match "/application.js" => Sprockets, :via => :all
|
||||
```
|
||||
|
||||
As long as +Sprockets+ responds to +call+ and returns a <tt>[status, headers, body]</tt>, the router won't know the difference between the Rack application and an action. This is an appropriate use of +:via => :all+, as you will want to allow your Rack application to handle all verbs as it considers appropriate.
|
||||
As long as +Sprockets+ responds to +call+ and returns a `[status, headers, body]`, the router won't know the difference between the Rack application and an action. This is an appropriate use of +:via => :all+, as you will want to allow your Rack application to handle all verbs as it considers appropriate.
|
||||
|
||||
NOTE: For the curious, +"posts#index"+ actually expands out to +PostsController.action(:index)+, which returns a valid Rack application.
|
||||
|
||||
|
|
|
@ -30,7 +30,7 @@ Capitalize all words except for internal articles, prepositions, conjunctions, a
|
|||
Use the same typography as in regular text:
|
||||
|
||||
```
|
||||
##### The <tt>:content_type</tt> Option
|
||||
##### The `:content_type` Option
|
||||
```
|
||||
|
||||
API Documentation Guidelines
|
||||
|
@ -77,7 +77,7 @@ To force processing all the guides, pass +ALL=1+.
|
|||
|
||||
It is also recommended that you work with +WARNINGS=1+. This detects duplicate IDs and warns about broken internal links.
|
||||
|
||||
If you want to generate guides in a language other than English, you can keep them in a separate directory under +source+ (eg. <tt>source/es</tt>) and use the +GUIDES_LANGUAGE+ environment variable:
|
||||
If you want to generate guides in a language other than English, you can keep them in a separate directory under +source+ (eg. `source/es`) and use the +GUIDES_LANGUAGE+ environment variable:
|
||||
|
||||
```
|
||||
bundle exec rake guides:generate GUIDES_LANGUAGE=es
|
||||
|
|
|
@ -236,7 +236,7 @@ There are many other possibilities, including Ajax to attack the victim in the b
|
|||
protect_from_forgery :secret => "123456789012345678901234567890..."
|
||||
```
|
||||
|
||||
This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. If the security token doesn't match what was expected, the session will be reset. *Note:* In Rails versions prior to 3.0.4, this raised an <tt>ActionController::InvalidAuthenticityToken</tt> error.
|
||||
This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. If the security token doesn't match what was expected, the session will be reset. *Note:* In Rails versions prior to 3.0.4, this raised an `ActionController::InvalidAuthenticityToken` error.
|
||||
|
||||
It is common to use persistent cookies to store user information, with +cookies.permanent+ for example. In this case, the cookies will not be cleared and the out of the box CSRF protection will not be effective. If you are using a different cookie store than the session for this information, you must handle what to do with it yourself:
|
||||
|
||||
|
@ -400,7 +400,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. 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 `attributes=` 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
|
||||
|
@ -465,7 +465,7 @@ When assigning attributes in Active Record using +attributes=+ the :default role
|
|||
@user.is_admin # => true
|
||||
```
|
||||
|
||||
In a similar way, +new+, +create+, <tt>create!</tt>, +update_attributes+, and +update_attributes!+ methods all respect mass-assignment security and accept either +:as+ or +:without_protection+ options. For example:
|
||||
In a similar way, +new+, +create+, `create!`, +update_attributes+, and +update_attributes!+ methods all respect mass-assignment security and accept either +:as+ or +:without_protection+ options. For example:
|
||||
|
||||
```ruby
|
||||
@user = User.new({ :name => 'Sebastian', :is_admin => true }, :as => :admin)
|
||||
|
@ -572,7 +572,7 @@ Note that this protects you only from automatic bots, targeted tailor-made bots
|
|||
|
||||
WARNING: _Tell Rails not to put passwords in the log files._
|
||||
|
||||
By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by appending them to <tt>config.filter_parameters</tt> in the application configuration. These parameters will be marked [FILTERED] in the log.
|
||||
By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by appending them to `config.filter_parameters` in the application configuration. These parameters will be marked [FILTERED] in the log.
|
||||
|
||||
```ruby
|
||||
config.filter_parameters << :password
|
||||
|
|
|
@ -35,28 +35,29 @@ The following changes are meant for upgrading your application to Rails 4.0.
|
|||
|
||||
### vendor/plugins
|
||||
|
||||
Rails 4.0 no longer supports loading plugins from <tt>vendor/plugins</tt>. You must replace any plugins by extracting them to gems and adding them to your Gemfile. If you choose not to make them gems, you can move them into, say, <tt>lib/my_plugin/*</tt> and add an appropriate initializer in <tt>config/initializers/my_plugin.rb</tt>.
|
||||
Rails 4.0 no longer supports loading plugins from `vendor/plugins`. You must replace any plugins by extracting them to gems and adding them to your Gemfile. If you choose not to make them gems, you can move them into, say, `lib/my_plugin/*` and add an appropriate initializer in `config/initializers/my_plugin.rb`.
|
||||
|
||||
### Identity Map
|
||||
|
||||
Rails 4.0 has removed the identity map from Active Record, due to "some inconsistencies with associations":https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6. If you have manually enabled it in your application, you will have to remove the following config that has no effect anymore: <tt>config.active_record.identity_map</tt>.
|
||||
Rails 4.0 has removed the identity map from Active Record, due to "some inconsistencies with associations":https://github.com/rails/rails/commit/302c912bf6bcd0fa200d964ec2dc4a44abe328a6. If you have manually enabled it in your application, you will have to remove the following config that has no effect anymore: `config.active_record.identity_map`.
|
||||
|
||||
### Active Record
|
||||
|
||||
The <tt>delete</tt> method in collection associations can now receive <tt>Fixnum</tt> or <tt>String</tt> arguments as record ids, besides records, pretty much like the <tt>destroy</tt> method does. Previously it raised <tt>ActiveRecord::AssociationTypeMismatch</tt> for such arguments. From Rails 4.0 on <tt>delete</tt> automatically tries to find the records matching the given ids before deleting them.
|
||||
The `delete` method in collection associations can now receive `Fixnum` or `String` arguments as record ids, besides records, pretty much like the `destroy` method does. Previously it raised `ActiveRecord::AssociationTypeMismatch` for such arguments. From Rails 4.0 on `delete` automatically tries to find the records matching the given ids before deleting them.
|
||||
|
||||
Rails 4.0 has changed how orders get stacked in +ActiveRecord::Relation+. In previous versions of rails new order was applied after previous defined order. But this is no long true. Check "ActiveRecord Query guide":active_record_querying.html#ordering for more information.
|
||||
Rails 4.0 has changed how orders get stacked in `ActiveRecord::Relation`. In previous versions of rails new order was applied after previous defined order. But this is no long true. Check "ActiveRecord Query guide":active_record_querying.html#ordering for more information.
|
||||
|
||||
Rails 4.0 has changed <tt>serialized_attributes</tt> and <tt>_attr_readonly</tt> to class methods only. Now you shouldn't use instance methods, it's deprecated. You must change them, e.g. <tt>self.serialized_attributes</tt> to <tt>self.class.serialized_attributes</tt>.
|
||||
Rails 4.0 has changed `serialized_attributes` and `attr_readonly` to class methods only. Now you shouldn't use instance methods, it's deprecated. You must change them, e.g. `self.serialized_attributes` to `self.class.serialized_attributes`.
|
||||
|
||||
### Active Model
|
||||
|
||||
Rails 4.0 has changed how errors attach with the <tt>ActiveModel::Validations::ConfirmationValidator</tt>. Now when confirmation validations fail the error will be attached to <tt>:#{attribute}_confirmation</tt> instead of <tt>attribute</tt>.
|
||||
Rails 4.0 has changed how errors attach with the `ActiveModel::Validations::ConfirmationValidator`. Now when confirmation validations fail the error will be attached to `:#{attribute}_confirmation` instead of `attribute`.
|
||||
|
||||
### Action Pack
|
||||
|
||||
Rails 4.0 changed how <tt>assert_generates</tt>, <tt>assert_recognizes</tt>, and <tt>assert_routing</tt> work. Now all these assertions raise <tt>Assertion</tt> instead of <tt>ActionController::RoutingError</tt>.
|
||||
Rails 4.0 changed how `assert_generates`, `assert_recognizes`, and `assert_routing` work. Now all these assertions raise `Assertion` instead of `ActionController::RoutingError`.
|
||||
|
||||
<<<<<<< HEAD
|
||||
Rails 4.0 also changed the way unicode character routes are drawn. Now you can draw unicode character routes directly. If you already draw such routes, you must change them, for example:
|
||||
|
||||
<ruby>
|
||||
|
@ -68,14 +69,17 @@ becomes
|
|||
<ruby>
|
||||
get 'こんにちは', :controller => 'welcome', :action => 'index'
|
||||
</ruby>
|
||||
=======
|
||||
Rails 4.0 also changed the way unicode character routes are drawn. Now you can draw unicode character routes directly. If you already draw such routes, you must change them, e.g. `get Rack::Utils.escape('こんにちは'), :controller => 'welcome', :action => 'index'` to `get 'こんにちは', :controller => 'welcome', :action => 'index'`.
|
||||
>>>>>>> Convert inline code tags to Markdown
|
||||
|
||||
### Active Support
|
||||
|
||||
Rails 4.0 Removed the <tt>j</tt> alias for <tt>ERB::Util#json_escape</tt> since <tt>j</tt> is already used for <tt>ActionView::Helpers::JavaScriptHelper#escape_javascript</tt>.
|
||||
Rails 4.0 Removed the `j` alias for `ERB::Util#json_escape` since `j` is already used for `ActionView::Helpers::JavaScriptHelper#escape_javascript`.
|
||||
|
||||
### Helpers Loading Order
|
||||
|
||||
The loading order of helpers from more than one directory has changed in Rails 4.0. Previously, helpers from all directories were gathered and then sorted alphabetically. After upgrade to Rails 4.0 helpers will preserve the order of loaded directories and will be sorted alphabetically only within each directory. Unless you explicitly use <tt>helpers_path</tt> parameter, this change will only impact the way of loading helpers from engines. If you rely on the fact that particular helper from engine loads before or after another helper from application or another engine, you should check if correct methods are available after upgrade. If you would like to change order in which engines are loaded, you can use <tt>config.railties_order=</tt> method.
|
||||
The loading order of helpers from more than one directory has changed in Rails 4.0. Previously, helpers from all directories were gathered and then sorted alphabetically. After upgrade to Rails 4.0 helpers will preserve the order of loaded directories and will be sorted alphabetically only within each directory. Unless you explicitly use `helpers_path` parameter, this change will only impact the way of loading helpers from engines. If you rely on the fact that particular helper from engine loads before or after another helper from application or another engine, you should check if correct methods are available after upgrade. If you would like to change order in which engines are loaded, you can use `config.railties_order=` method.
|
||||
|
||||
Upgrading from Rails 3.1 to Rails 3.2
|
||||
-------------------------------------
|
||||
|
@ -86,7 +90,7 @@ The following changes are meant for upgrading your application to Rails 3.2.2, t
|
|||
|
||||
### Gemfile
|
||||
|
||||
Make the following changes to your +Gemfile+.
|
||||
Make the following changes to your `Gemfile`.
|
||||
|
||||
```ruby
|
||||
gem 'rails', '= 3.2.2'
|
||||
|
@ -113,7 +117,7 @@ config.active_record.auto_explain_threshold_in_seconds = 0.5
|
|||
|
||||
### config/environments/test.rb
|
||||
|
||||
The <tt>mass_assignment_sanitizer</tt> configuration setting should also be be added to <tt>config/environments/test.rb</tt>:
|
||||
The `mass_assignment_sanitizer` configuration setting should also be be added to `config/environments/test.rb`:
|
||||
|
||||
```ruby
|
||||
# Raise exception on mass assignment protection for Active Record models
|
||||
|
@ -122,7 +126,7 @@ config.active_record.mass_assignment_sanitizer = :strict
|
|||
|
||||
### vendor/plugins
|
||||
|
||||
Rails 3.2 deprecates <tt>vendor/plugins</tt> and Rails 4.0 will remove them completely. While it's not strictly necessary as part of a Rails 3.2 upgrade, you can start replacing any plugins by extracting them to gems and adding them to your Gemfile. If you choose not to make them gems, you can move them into, say, <tt>lib/my_plugin/*</tt> and add an appropriate initializer in <tt>config/initializers/my_plugin.rb</tt>.
|
||||
Rails 3.2 deprecates `vendor/plugins` and Rails 4.0 will remove them completely. While it's not strictly necessary as part of a Rails 3.2 upgrade, you can start replacing any plugins by extracting them to gems and adding them to your Gemfile. If you choose not to make them gems, you can move them into, say, `lib/my_plugin/*` and add an appropriate initializer in `config/initializers/my_plugin.rb`.
|
||||
|
||||
Upgrading from Rails 3.0 to Rails 3.1
|
||||
-------------------------------------
|
||||
|
@ -133,7 +137,7 @@ The following changes are meant for upgrading your application to Rails 3.1.3, t
|
|||
|
||||
### Gemfile
|
||||
|
||||
Make the following changes to your +Gemfile+.
|
||||
Make the following changes to your `Gemfile`.
|
||||
|
||||
```ruby
|
||||
gem 'rails', '= 3.1.3'
|
||||
|
@ -168,7 +172,7 @@ config.assets.prefix = '/asset-files'
|
|||
|
||||
### config/environments/development.rb
|
||||
|
||||
Remove the RJS setting <tt>config.action_view.debug_rjs = true</tt>.
|
||||
Remove the RJS setting `config.action_view.debug_rjs = true`.
|
||||
|
||||
Add these settings if you enable the asset pipeline:
|
||||
|
||||
|
|
Loading…
Reference in New Issue