Merge branch 'master' of github.com:lifo/docrails

Conflicts:
	guides/source/active_record_validations.md
This commit is contained in:
Vijay Dev 2012-12-01 23:00:47 +05:30
commit 0181c2da97
40 changed files with 296 additions and 258 deletions

View File

@ -672,7 +672,11 @@ module ActiveRecord
end
# Returns the size of the collection. If the collection hasn't been loaded,
# it executes a <tt>SELECT COUNT(*)</tt> query.
# it executes a <tt>SELECT COUNT(*)</tt> query. Else it calls <tt>collection.size</tt>.
#
# If the collection has been already loaded +size+ and +length+ are
# equivalent. If not and you are going to need the records anyway
# +length+ will take one less query. Otherwise +size+ is more efficient.
#
# class Person < ActiveRecord::Base
# has_many :pets
@ -697,7 +701,8 @@ module ActiveRecord
# Returns the size of the collection calling +size+ on the target.
# If the collection has been already loaded, +length+ and +size+ are
# equivalent.
# equivalent. If not and you are going to need the records anyway this
# method will take one less query. Otherwise +size+ is more efficient.
#
# class Person < ActiveRecord::Base
# has_many :pets
@ -718,7 +723,12 @@ module ActiveRecord
@association.length
end
# Returns +true+ if the collection is empty.
# Returns +true+ if the collection is empty. If the collection has been
# loaded or the <tt>:counter_sql</tt> option is provided, it is equivalent
# to <tt>collection.size.zero?</tt>. If the collection has not been loaded,
# it is equivalent to <tt>collection.exists?</tt>. If the collection has
# not already been loaded and you are going to fetch the records anyway it
# is better to check <tt>collection.length.zero?</tt>.
#
# class Person < ActiveRecord::Base
# has_many :pets

View File

@ -111,8 +111,8 @@ module ActiveRecord
0
end
# Use <tt>pluck</tt> as a shortcut to select a single attribute without
# loading a bunch of records just to grab one attribute you want.
# Use <tt>pluck</tt> as a shortcut to select one or more attributes without
# loading a bunch of records just to grab the attributes you want.
#
# Person.pluck(:name)
#
@ -121,7 +121,7 @@ module ActiveRecord
# Person.all.map(&:name)
#
# Pluck returns an <tt>Array</tt> of attribute values type-casted to match
# the plucked column name, if it can be deduced. Plucking an SQL fragment
# the plucked column names, if they can be deduced. Plucking an SQL fragment
# returns String values by default.
#
# Examples:

View File

@ -3,13 +3,13 @@ require 'active_support/core_ext/module/delegation'
module ActiveSupport
class Deprecation
module InstanceDelegator
module InstanceDelegator # :nodoc:
def self.included(base)
base.extend(ClassMethods)
base.public_class_method :new
end
module ClassMethods
module ClassMethods # :nodoc:
def include(included_module)
included_module.instance_methods.each { |m| method_added(m) }
super
@ -21,4 +21,4 @@ module ActiveSupport
end
end
end
end
end

View File

@ -1,15 +1,17 @@
Action Controller Overview
==========================
In this guide you will learn how controllers work and how they fit into the request cycle in your application. After reading this guide, you will be able to:
In this guide you will learn how controllers work and how they fit into the request cycle in your application.
* Follow the flow of a request through a controller
* Understand why and how to store data in the session or cookies
* Work with filters to execute code during request processing
* Use Action Controller's built-in HTTP authentication
* Stream data directly to the user's browser
* Filter sensitive parameters so they do not appear in the application's log
* Deal with exceptions that may be raised during request processing
After reading this guide, you will know:
* Follow the flow of a request through a controller.
* Understand why and how to store data in the session or cookies.
* Work with filters to execute code during request processing.
* Use Action Controller's built-in HTTP authentication.
* Stream data directly to the user's browser.
* Filter sensitive parameters so they do not appear in the application's log.
* Deal with exceptions that may be raised during request processing.
--------------------------------------------------------------------------------

View File

@ -3,9 +3,9 @@ Action Mailer Basics
This guide should provide you with all you need to get started in sending and receiving emails from and to your application, and many internals of Action Mailer. It also covers how to test your mailers.
--------------------------------------------------------------------------------
After reading this guide, you will know:
WARNING. This guide is based on Rails 3.2. Some of the code shown here will not work in earlier versions of Rails.
--------------------------------------------------------------------------------
Introduction
------------

View File

@ -1,13 +1,13 @@
Action View Overview
====================
In this guide you will learn:
After reading this guide, you will know:
* What Action View is and how to use it with Rails
* How best to use templates, partials, and layouts
* What helpers are provided by Action View and how to make your own
* How to use localized views
* How to use Action View outside of Rails
* What Action View is and how to use it with Rails.
* How best to use templates, partials, and layouts.
* What helpers are provided by Action View and how to make your own.
* How to use localized views.
* How to use Action View outside of Rails.
--------------------------------------------------------------------------------

View File

@ -1,12 +1,12 @@
Active Model Basics
===================
This guide should provide you with all you need to get started using model classes. Active Model allows for Action Pack helpers to interact with non-ActiveRecord models. Active Model also helps building custom ORMs for use outside of the Rails framework.
This guide should provide you with all you need to get started using model classes. Active Model allows for Action Pack helpers to interact with non-Active Record models. Active Model also helps building custom ORMs for use outside of the Rails framework.
After reading this guide, you will know:
--------------------------------------------------------------------------------
WARNING. This guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.
Introduction
------------

View File

@ -1,13 +1,15 @@
Active Record Basics
====================
This guide is an introduction to Active Record. After reading this guide we hope that you'll learn:
This guide is an introduction to Active Record.
* What Object Relational Mapping and Active Record are and how they are used in Rails
* How Active Record fits into the Model-View-Controller paradigm
* How to use Active Record models to manipulate data stored in a relational database
* Active Record schema naming conventions
* The concepts of database migrations, validations and callbacks
After reading this guide, you will know:
* What Object Relational Mapping and Active Record are and how they are used in Rails.
* How Active Record fits into the Model-View-Controller paradigm.
* How to use Active Record models to manipulate data stored in a relational database.
* Active Record schema naming conventions.
* The concepts of database migrations, validations and callbacks.
--------------------------------------------------------------------------------

View File

@ -1,15 +1,17 @@
Active Record Query Interface
=============================
This guide covers different ways to retrieve data from the database using Active Record. By referring to this guide, you will be able to:
This guide covers different ways to retrieve data from the database using Active Record.
* Find records using a variety of methods and conditions
* Specify the order, retrieved attributes, grouping, and other properties of the found records
* Use eager loading to reduce the number of database queries needed for data retrieval
* Use dynamic finders methods
* Check for the existence of particular records
* Perform various calculations on Active Record models
* Run EXPLAIN on relations
After reading this guide, you will know:
* Find records using a variety of methods and conditions.
* Specify the order, retrieved attributes, grouping, and other properties of the found records.
* Use eager loading to reduce the number of database queries needed for data retrieval.
* Use dynamic finders methods.
* Check for the existence of particular records.
* Perform various calculations on Active Record models.
* Run EXPLAIN on relations.
--------------------------------------------------------------------------------
@ -466,7 +468,7 @@ The field name can also be a string:
Client.where('locked' => true)
```
In the case of a belongs_to relationship, an association key can be used to specify the model if an ActiveRecord object is used as the value. This method works with polymorphic relationships as well.
In the case of a belongs_to relationship, an association key can be used to specify the model if an Active Record object is used as the value. This method works with polymorphic relationships as well.
```ruby
Post.where(author: author)

View File

@ -4,14 +4,14 @@ Active Record Validations
This guide teaches you how to validate the state of objects before they go into
the database using Active Record's validations feature.
After reading this guide and trying out the presented concepts, we hope that you'll be able to:
After reading this guide, you will know:
* Understand the life cycle of Active Record objects
* Use the built-in Active Record validation helpers
* Create your own custom validation methods
* Work with the error messages generated by the validation process
* Create callback methods that respond to events in the object life cycle
* Create special classes that encapsulate common behavior for your callbacks
* Understand the life cycle of Active Record objects.
* Use the built-in Active Record validation helpers.
* Create your own custom validation methods.
* Work with the error messages generated by the validation process.
* Create callback methods that respond to events in the object life cycle.
* Create special classes that encapsulate common behavior for your callbacks.
--------------------------------------------------------------------------------
@ -365,12 +365,20 @@ class Person < ActiveRecord::Base
end
```
If you want to be sure that an association is present, you'll need to test whether the foreign key used to map the association is present, and not the associated object itself.
If you want to be sure that an association is present, you'll need to test the associated object itself, and not whether the foreign key used to map the association is present:
```ruby
class LineItem < ActiveRecord::Base
belongs_to :order
validates :order_id, presence: true
validates :order, presence: true
end
```
You should also be sure to have a proper `:inverse_of` as well:
```ruby
class Order < ActiveRecord::Base
has_many :line_items, inverse_of: :order
end
```
@ -667,7 +675,7 @@ class Invoice < ActiveRecord::Base
:discount_cannot_be_greater_than_total_value
def expiration_date_cannot_be_in_the_past
if !expiration_date.blank? and expiration_date < Date.today
if expiration_date.present? && expiration_date < Date.today
errors.add(:expiration_date, "can't be in the past")
end
end

View File

@ -5,7 +5,7 @@ Active Support is the Ruby on Rails component responsible for providing Ruby lan
It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Ruby on Rails itself.
By referring to this guide you will learn the extensions to the Ruby core classes and modules provided by Active Support.
After reading this guide, you will know:
--------------------------------------------------------------------------------

View File

@ -3,19 +3,21 @@ Active Support Instrumentation
Active Support is a part of core Rails that provides Ruby language extensions, utilities and other things. One of the things it includes is an instrumentation API that can be used inside an application to measure certain actions that occur within Ruby code, such as that inside a Rails application or the framework itself. It is not limited to Rails, however. It can be used independently in other Ruby scripts if it is so desired.
In this guide, you will learn how to use the instrumentation API inside of ActiveSupport to measure events inside of Rails and other Ruby code. We cover:
In this guide, you will learn how to use the instrumentation API inside of Active Support to measure events inside of Rails and other Ruby code.
* What instrumentation can provide
* The hooks inside the Rails framework for instrumentation
* Adding a subscriber to a hook
* Building a custom instrumentation implementation
After reading this guide, you will know:
* What instrumentation can provide.
* The hooks inside the Rails framework for instrumentation.
* Adding a subscriber to a hook.
* Building a custom instrumentation implementation.
--------------------------------------------------------------------------------
Introduction to instrumentation
-------------------------------
The instrumentation API provided by ActiveSupport allows developers to provide hooks which other developers may hook into. There are several of these within the Rails framework, as described below in <TODO: link to section detailing each hook point>. With this API, developers can choose to be notified when certain events occur inside their application or another piece of Ruby code.
The instrumentation API provided by Active Support allows developers to provide hooks which other developers may hook into. There are several of these within the Rails framework, as described below in <TODO: link to section detailing each hook point>. With this API, developers can choose to be notified when certain events occur inside their application or another piece of Ruby code.
For example, there is a hook provided within Active Record that is called every time Active Record uses an SQL query on a database. This hook could be **subscribed** to, and used to track the number of queries during a certain action. There's another hook around the processing of an action of a controller. This could be used, for instance, to track how long a specific action has taken.
@ -26,8 +28,8 @@ Rails framework hooks
Within the Ruby on Rails framework, there are a number of hooks provided for common events. These are detailed below.
ActionController
----------------
Action Controller
-----------------
### write_fragment.action_controller
@ -187,8 +189,8 @@ INFO. Additional keys may be added by the caller.
}
```
ActionView
----------
Action View
-----------
### render_template.action_view
@ -216,7 +218,7 @@ ActionView
}
```
ActiveRecord
Active Record
------------
### sql.active_record
@ -246,8 +248,8 @@ INFO. The adapters will add their own data as well.
| `:name` | Record's class |
| `:connection_id` | `self.object_id` |
ActionMailer
------------
Action Mailer
-------------
### receive.action_mailer
@ -312,8 +314,8 @@ ActiveResource
| `:request_uri` | Complete URI |
| `:result` | HTTP response object |
ActiveSupport
-------------
Active Support
--------------
### cache_read.active_support

View File

@ -3,6 +3,8 @@ API Documentation Guidelines
This guide documents the Ruby on Rails API documentation guidelines.
After reading this guide, you will know:
--------------------------------------------------------------------------------
RDoc

View File

@ -1,14 +1,15 @@
Asset Pipeline
==============
The Asset Pipeline
==================
This guide covers the asset pipeline introduced in Rails 3.1.
By referring to this guide you will be able to:
* Understand what the asset pipeline is and what it does
* Properly organize your application assets
* Understand the benefits of the asset pipeline
* Add a pre-processor to the pipeline
* Package assets with a gem
After reading this guide, you will know:
* Understand what the asset pipeline is and what it does.
* Properly organize your application assets.
* Understand the benefits of the asset pipeline.
* Add a pre-processor to the pipeline.
* Package assets with a gem.
--------------------------------------------------------------------------------

View File

@ -1,11 +1,13 @@
A Guide to Active Record Associations
=====================================
Active Record Associations
==========================
This guide covers the association features of Active Record. By referring to this guide, you will be able to:
This guide covers the association features of Active Record.
* Declare associations between Active Record models
* Understand the various types of Active Record associations
* Use the methods added to your models by creating associations
After reading this guide, you will know:
* Declare associations between Active Record models.
* Understand the various types of Active Record associations.
* Use the methods added to your models by creating associations.
--------------------------------------------------------------------------------

View File

@ -3,12 +3,12 @@ Caching with Rails: An overview
This guide will teach you what you need to know about avoiding that expensive round-trip to your database and returning what you need to return to the web clients in the shortest time possible.
After reading this guide, you should be able to use and configure:
After reading this guide, you will know:
* Page, action, and fragment caching
* Sweepers
* Alternative cache stores
* Conditional GET support
* Page, action, and fragment caching.
* Sweepers.
* Alternative cache stores.
* Conditional GET support.
--------------------------------------------------------------------------------

View File

@ -1,20 +1,20 @@
A Guide to The Rails Command Line
=================================
The Rails Command Line
======================
Rails comes with every command line tool you'll need to
* Create a Rails application
* Generate models, controllers, database migrations, and unit tests
* Start a development server
* Experiment with objects through an interactive shell
* Profile and benchmark your new creation
After reading this guide, you will know:
* Create a Rails application.
* Generate models, controllers, database migrations, and unit tests.
* Start a development server.
* Experiment with objects through an interactive shell.
* Profile and benchmark your new creation.
--------------------------------------------------------------------------------
NOTE: This tutorial assumes you have basic Rails knowledge from reading the [Getting Started with Rails Guide](getting_started.html).
WARNING. This Guide is based on Rails 3.2. Some of the code shown here will not work in earlier versions of Rails.
Command Line Basics
-------------------

View File

@ -1,10 +1,12 @@
Configuring Rails Applications
==============================
This guide covers the configuration and initialization features available to Rails applications. By referring to this guide, you will be able to:
This guide covers the configuration and initialization features available to Rails applications.
* Adjust the behavior of your Rails applications
* Add additional code to be run at application start time
After reading this guide, you will know:
* Adjust the behavior of your Rails applications.
* Add additional code to be run at application start time.
--------------------------------------------------------------------------------

View File

@ -1,13 +1,15 @@
Contributing to Ruby on Rails
=============================
This guide covers ways in which _you_ can become a part of the ongoing development of Ruby on Rails. After reading it, you should be familiar with:
This guide covers ways in which _you_ can become a part of the ongoing development of Ruby on Rails.
* Using GitHub to report issues
* Cloning master and running the test suite
* Helping to resolve existing issues
* Contributing to the Ruby on Rails documentation
* Contributing to the Ruby on Rails code
After reading this guide, you will know:
* Using GitHub to report issues.
* Cloning master and running the test suite.
* Helping to resolve existing issues.
* Contributing to the Ruby on Rails documentation.
* Contributing to the Ruby on Rails code.
Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation — all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.

View File

@ -1,12 +1,14 @@
Debugging Rails Applications
============================
This guide introduces techniques for debugging Ruby on Rails applications. By referring to this guide, you will be able to:
This guide introduces techniques for debugging Ruby on Rails applications.
* Understand the purpose of debugging
* Track down problems and issues in your application that your tests aren't identifying
* Learn the different ways of debugging
* Analyze the stack trace
After reading this guide, you will know:
* Understand the purpose of debugging.
* Track down problems and issues in your application that your tests aren't identifying.
* Learn the different ways of debugging.
* Analyze the stack trace.
--------------------------------------------------------------------------------

View File

@ -3,6 +3,8 @@ Development Dependencies Install
This guide covers how to setup an environment for Ruby on Rails core development.
After reading this guide, you will know:
--------------------------------------------------------------------------------
The Easy Way

View File

@ -1,13 +1,15 @@
Getting Started with Engines
============================
In this guide you will learn about engines and how they can be used to provide additional functionality to their host applications through a clean and very easy-to-use interface. You will learn the following things in this guide:
In this guide you will learn about engines and how they can be used to provide additional functionality to their host applications through a clean and very easy-to-use interface.
* What makes an engine
* How to generate an engine
* Building features for the engine
* Hooking the engine into an application
* Overriding engine functionality in the application
After reading this guide, you will know:
* What makes an engine.
* How to generate an engine.
* Building features for the engine.
* Hooking the engine into an application.
* Overriding engine functionality in the application.
--------------------------------------------------------------------------------

View File

@ -1,17 +1,17 @@
Rails Form helpers
==================
Form Helpers
============
Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails deals away with these complexities by providing view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.
In this guide you will:
After reading this guide, you will know:
* Create search forms and similar kind of generic forms not representing any specific model in your application
* Make model-centric forms for creation and editing of specific database records
* Generate select boxes from multiple types of data
* Understand the date and time helpers Rails provides
* Learn what makes a file upload form different
* Learn some cases of building forms to external resources
* Find out how to build complex forms
* Create search forms and similar kind of generic forms not representing any specific model in your application.
* Make model-centric forms for creation and editing of specific database records.
* Generate select boxes from multiple types of data.
* Understand the date and time helpers Rails provides.
* Learn what makes a file upload form different.
* Learn some cases of building forms to external resources.
* Find out how to build complex forms.
--------------------------------------------------------------------------------

View File

@ -3,15 +3,15 @@ Creating and Customizing Rails Generators & Templates
Rails generators are an essential tool if you plan to improve your workflow. With this guide you will learn how to create generators and customize existing ones.
In this guide you will:
After reading this guide, you will know:
* Learn how to see which generators are available in your application
* Create a generator using templates
* Learn how Rails searches for generators before invoking them
* Customize your scaffold by creating new generators
* Customize your scaffold by changing generator templates
* Learn how to use fallbacks to avoid overwriting a huge set of generators
* Learn how to create an application template
* Learn how to see which generators are available in your application.
* Create a generator using templates.
* Learn how Rails searches for generators before invoking them.
* Customize your scaffold by creating new generators.
* Customize your scaffold by changing generator templates.
* Learn how to use fallbacks to avoid overwriting a huge set of generators.
* Learn how to create an application template.
--------------------------------------------------------------------------------

View File

@ -1,8 +1,9 @@
Getting Started with Rails
==========================
This guide covers getting up and running with Ruby on Rails. After reading it,
you should be familiar with:
This guide covers getting up and running with Ruby on Rails.
After reading this guide, you will know:
* Installing Rails, creating a new Rails application, and connecting your
application to a database.
@ -12,9 +13,6 @@ you should be familiar with:
--------------------------------------------------------------------------------
WARNING. This Guide is based on Rails 3.2. Some of the code shown here will not
work in earlier versions of Rails.
Guide Assumptions
-----------------
@ -24,7 +22,7 @@ with Rails. However, to get the most out of it, you need to have some
prerequisites installed:
* The [Ruby](http://www.ruby-lang.org/en/downloads) language version 1.9.3 or higher
* The [RubyGems](http://rubyforge.org/frs/?group_id=126) packaging system
* The [RubyGems](http://rubygems.org/) packaging system
* To learn more about RubyGems, please read the [RubyGems User Guide](http://docs.rubygems.org/read/book/1)
* A working installation of the [SQLite3 Database](http://www.sqlite.org)
@ -77,11 +75,14 @@ TIP: The examples below use # and $ to denote superuser and regular user termina
### Installing Rails
Open up a command line prompt. On a mac this is called terminal, on windows it is called command prompt. Any commands prefaced with a dollar sign `$` should be run in the command line. Verify sure you have a current version of Ruby installed:
Open up a command line prompt. On Mac OS X open Terminal.app, on Windows choose
"Run" from your Start menu and type 'cmd.exe'. Any commands prefaced with a
dollar sign `$` should be run in the command line. Verify sure you have a
current version of Ruby installed:
```bash
$ ruby -v
ruby 1.9.3p194
ruby 1.9.3p327
```
To install Rails, use the `gem install` command provided by RubyGems:
@ -100,7 +101,7 @@ To verify that you have everything installed correctly, you should be able to ru
$ rails --version
```
If it says something like "Rails 3.2.8" you are ready to continue.
If it says something like "Rails 3.2.9" you are ready to continue.
### Creating the Blog Application
@ -165,7 +166,7 @@ This will fire up WEBrick, a webserver built into Ruby by default. To see your a
![Welcome Aboard screenshot](images/rails_welcome.png)
TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. To verify the server has stopped you should see your command prompt cursor again. For most unix like systems including mac this will be a dollar sign `$`. In development mode, Rails does not generally require you to restart the server; changes you make in files will be automatically picked up by the server.
TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. To verify the server has stopped you should see your command prompt cursor again. For most UNIX-like systems including Mac OS X this will be a dollar sign `$`. In development mode, Rails does not generally require you to restart the server; changes you make in files will be automatically picked up by the server.
The "Welcome Aboard" page is the _smoke test_ for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page. You can also click on the _About your applications environment_ link to see a summary of your application's environment.
@ -702,19 +703,6 @@ your Rails models for free, including basic database CRUD (Create, Read, Update,
Destroy) operations, data validation, as well as sophisticated search support
and the ability to relate multiple models to one another.
Rails includes methods to help you secure some of your model fields.
Open the `app/models/post.rb` file and edit it:
```ruby
class Post < ActiveRecord::Base
attr_accessible :text, :title
end
```
This change will ensure that all changes made through HTML forms can edit the content of the text and title fields.
It will not be possible to define any other field value through forms. You can still define them by calling the `field=` method of course.
Accessible attributes and the mass assignment problem is covered in details in the [Security guide](security.html#mass-assignment)
### Adding Some Validation
Rails includes methods to help you validate the data that you send to models.
@ -722,8 +710,6 @@ Open the `app/models/post.rb` file and edit it:
```ruby
class Post < ActiveRecord::Base
attr_accessible :text, :title
validates :title, presence: true,
length: { minimum: 5 }
end
@ -960,35 +946,14 @@ And here's how our app looks so far:
### Using partials to clean up duplication in views
`partials` are what Rails uses to remove duplication in views. Here's a
simple example:
```html+erb
# app/views/user/show.html.erb
<h1><%= @user.name %></h1>
<%= render 'user_details' %>
# app/views/user/_user_details.html.erb
<%= @user.location %>
<%= @user.about_me %>
```
The `users/show` template will automatically include the content of the
`users/_user_details` template. Note that partials are prefixed by an underscore,
as to not be confused with regular views. However, you don't include the
underscore when including them with the `helper` method.
Our `edit` page looks very similar to the `new` page, in fact they
both share the same code for displaying the form. Let's remove some duplication
by using a view partial. By convention, partial files are prefixed by an
underscore.
TIP: You can read more about partials in the
[Layouts and Rendering in Rails](layouts_and_rendering.html) guide.
Our `edit` action looks very similar to the `new` action, in fact they
both share the same code for displaying the form. Let's clean them up by
using a partial.
Create a new file `app/views/posts/_form.html.erb` with the following
content:
@ -1150,7 +1115,8 @@ together.
<td><%= post.text %></td>
<td><%= link_to 'Show', action: :show, id: post.id %></td>
<td><%= link_to 'Edit', action: :edit, id: post.id %></td>
<td><%= link_to 'Destroy', { action: :destroy, id: post.id }, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<td><%= link_to 'Destroy', { action: :destroy, id: post.id },
method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</table>
@ -1255,7 +1221,6 @@ First, take a look at `comment.rb`:
```ruby
class Comment < ActiveRecord::Base
belongs_to :post
attr_accessible :body, :commenter
end
```
@ -1312,7 +1277,7 @@ this way:
* One post can have many comments.
In fact, this is very close to the syntax that Rails uses to declare this
association. You've already seen the line of code inside the Comment model that
association. You've already seen the line of code inside the `Comment` model that
makes each comment belong to a Post:
```ruby
@ -1325,10 +1290,10 @@ You'll need to edit the `post.rb` file to add the other side of the association:
```ruby
class Post < ActiveRecord::Base
has_many :comments
validates :title, presence: true,
length: { minimum: 5 }
has_many :comments
[...]
end
```
@ -1428,7 +1393,7 @@ class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_url(@post)
redirect_to post_path(@post)
end
end
```
@ -1679,9 +1644,10 @@ model, `app/models/post.rb`, as follows:
```ruby
class Post < ActiveRecord::Base
has_many :comments, dependent: :destroy
validates :title, presence: true,
length: { minimum: 5 }
has_many :comments, dependent: :destroy
[...]
end
```

View File

@ -7,18 +7,20 @@ The process of "internationalization" usually means to abstract all strings and
So, in the process of _internationalizing_ your Rails application you have to:
* Ensure you have support for i18n
* Tell Rails where to find locale dictionaries
* Tell Rails how to set, preserve and switch locales
* Ensure you have support for i18n.
* Tell Rails where to find locale dictionaries.
* Tell Rails how to set, preserve and switch locales.
In the process of _localizing_ your application you'll probably want to do the following three things:
* Replace or supplement Rails' default locale — e.g. date and time formats, month names, Active Record model names, etc.
* Abstract strings in your application into keyed dictionaries — e.g. flash messages, static text in your views, etc.
* Store the resulting dictionaries somewhere
* Store the resulting dictionaries somewhere.
This guide will walk you through the I18n API and contains a tutorial on how to internationalize a Rails application from the start.
After reading this guide, you will know:
--------------------------------------------------------------------------------
NOTE: The Ruby I18n framework provides you with all necessary means for internationalization/localization of your Rails application. You may, however, use any of various plugins and extensions available, which add additional functionality or features. See the Rails [I18n Wiki](http://rails-i18n.org/wiki) for more information.

View File

@ -4,7 +4,9 @@ The Rails Initialization Process
This guide explains the internals of the initialization process in Rails
as of Rails 4. It is an extremely in-depth guide and recommended for advanced Rails developers.
* Using `rails server`
After reading this guide, you will know:
* Using `rails server`.
--------------------------------------------------------------------------------

View File

@ -3,10 +3,12 @@ Layouts and Rendering in Rails
This guide covers the basic layout features of Action Controller and Action View. By referring to this guide, you will be able to:
* Use the various rendering methods built into Rails
* Create layouts with multiple content sections
* Use partials to DRY up your views
* Use nested layouts (sub-templates)
After reading this guide, you will know:
* Use the various rendering methods built into Rails.
* Create layouts with multiple content sections.
* Use partials to DRY up your views.
* Use nested layouts (sub-templates).
--------------------------------------------------------------------------------

View File

@ -1,5 +1,22 @@
Migrations
==========
Active Record Migrations
========================
Migrations are a feature of Active Record that allows you to evolve your
database schema over time. Rather than write schema modifications in pure SQL,
migrations allow you to use an easy Ruby DSL to describe changes to your
tables.
After reading this guide, you will know:
* The generators you can use to create them.
* The methods Active Record provides to manipulate your database.
* The Rake tasks that manipulate migrations and your schema.
* How migrations relate to `schema.rb`.
--------------------------------------------------------------------------------
What are Migrations?
--------------------
Migrations are a convenient way for you to alter your database in a structured
and organized manner. You could edit fragments of SQL by hand but you would then
@ -9,7 +26,8 @@ production machines next time you deploy.
Active Record tracks which migrations have already been run so all you have to
do is update your source and run `rake db:migrate`. Active Record will work out
which migrations should be run. Active Record will also update your `db/schema.rb` file to match the up-to-date structure of your database.
which migrations should be run. Active Record will also update your
`db/schema.rb` file to match the up-to-date structure of your database.
Migrations also allow you to describe these transformations using Ruby. The
great thing about this is that (like most of Active Record's functionality) it
@ -18,15 +36,6 @@ is database independent: you don't need to worry about the precise syntax of
drop down to raw SQL for database specific features). For example, you could use
SQLite3 in development, but MySQL in production.
In this guide, you'll learn all about migrations including:
* The generators you can use to create them
* The methods Active Record provides to manipulate your database
* The Rake tasks that manipulate them
* How they relate to `schema.rb`
--------------------------------------------------------------------------------
Anatomy of a Migration
----------------------

View File

@ -3,9 +3,9 @@ Rails nested model forms
Creating a form for a model _and_ its associations can become quite tedious. Therefore Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations.
In this guide you will:
After reading this guide, you will know:
* do stuff
* do stuff.
--------------------------------------------------------------------------------

View File

@ -2,7 +2,9 @@ Performance Testing Rails Applications
======================================
This guide covers the various ways of performance testing a Ruby on Rails
application. By referring to this guide, you will be able to:
application.
After reading this guide, you will know:
* Understand the various types of benchmarking and profiling metrics.
* Generate performance and benchmarking tests.

View File

@ -7,15 +7,15 @@ A Rails plugin is either an extension or a modification of the core framework. P
* a segmented architecture so that units of code can be fixed or updated on their own release schedule
* an outlet for the core developers so that they dont have to include every cool new feature under the sun
After reading this guide you should be familiar with:
After reading this guide, you will know:
* Creating a plugin from scratch
* Writing and running tests for the plugin
* Creating a plugin from scratch.
* Writing and running tests for the plugin.
This guide describes how to build a test-driven plugin that will:
* Extend core Ruby classes like Hash and String
* Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins
* Extend core Ruby classes like Hash and String.
* Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins.
* Give you information about where to put generators in your plugin.
For the purpose of this guide pretend for a moment that you are an avid bird watcher.

View File

@ -3,10 +3,10 @@ Rails Application Templates
Application templates are simple Ruby files containing DSL for adding gems/initializers etc. to your freshly created Rails project or an existing Rails project.
By referring to this guide, you will be able to:
After reading this guide, you will know:
* Use templates to generate/customize Rails applications
* Write your own reusable application templates using the Rails template API
* Use templates to generate/customize Rails applications.
* Write your own reusable application templates using the Rails template API.
--------------------------------------------------------------------------------

View File

@ -1,12 +1,14 @@
Rails on Rack
=============
This guide covers Rails integration with Rack and interfacing with other Rack components. By referring to this guide, you will be able to:
This guide covers Rails integration with Rack and interfacing with other Rack components.
* Create Rails Metal applications
* Use Rack Middlewares in your Rails applications
* Understand Action Pack's internal Middleware stack
* Define a custom Middleware stack
After reading this guide, you will know:
* Create Rails Metal applications.
* Use Rack Middlewares in your Rails applications.
* Understand Action Pack's internal Middleware stack.
* Define a custom Middleware stack.
--------------------------------------------------------------------------------

View File

@ -1,13 +1,15 @@
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:
This guide covers the user-facing features of Rails routing.
* Understand the code in `routes.rb`
* 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
After reading this guide, you will know:
* Understand the code in `routes.rb`.
* 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.
--------------------------------------------------------------------------------

View File

@ -3,6 +3,8 @@ Ruby on Rails Guides Guidelines
This guide documents guidelines for writing Ruby on Rails Guides. This guide follows itself in a graceful loop, serving itself as an example.
After reading this guide, you will know:
--------------------------------------------------------------------------------
Markdown

View File

@ -1,15 +1,17 @@
Ruby On Rails Security Guide
============================
This manual describes common security problems in web applications and how to avoid them with Rails. After reading it, you should be familiar with:
This manual describes common security problems in web applications and how to avoid them with Rails.
* All countermeasures _that are highlighted_
* The concept of sessions in Rails, what to put in there and popular attack methods
* How just visiting a site can be a security problem (with CSRF)
* What you have to pay attention to when working with files or providing an administration interface
* The Rails-specific mass assignment problem
* How to manage users: Logging in and out and attack methods on all layers
* And the most popular injection attack methods
After reading this guide, you will know:
* All countermeasures _that are highlighted_.
* The concept of sessions in Rails, what to put in there and popular attack methods.
* How just visiting a site can be a security problem (with CSRF).
* What you have to pay attention to when working with files or providing an administration interface.
* The Rails-specific mass assignment problem.
* How to manage users: Logging in and out and attack methods on all layers.
* And the most popular injection attack methods.
--------------------------------------------------------------------------------

View File

@ -2,11 +2,13 @@ A Guide to Testing Rails Applications
=====================================
This guide covers built-in mechanisms offered by Rails to test your
application. By referring to this guide, you will be able to:
application.
* Understand Rails testing terminology
* Write unit, functional, and integration tests for your application
* Identify other popular testing approaches and plugins
After reading this guide, you will know:
* Understand Rails testing terminology.
* Write unit, functional, and integration tests for your application.
* Identify other popular testing approaches and plugins.
--------------------------------------------------------------------------------
@ -97,9 +99,9 @@ Rails by default automatically loads all fixtures from the `test/fixtures` folde
* Load the fixture data into the table
* Dump the fixture data into a variable in case you want to access it directly
#### Fixtures are ActiveRecord objects
#### Fixtures are Active Record objects
Fixtures are instances of ActiveRecord. As mentioned in point #3 above, you can access the object directly because it is automatically setup as a local variable of the test case. For example:
Fixtures are instances of Active Record. As mentioned in point #3 above, you can access the object directly because it is automatically setup as a local variable of the test case. For example:
```ruby
# this will return the User object for the fixture named david

View File

@ -3,6 +3,8 @@ A Guide for Upgrading Ruby on Rails
This guide provides steps to be followed when you upgrade your applications to a newer version of Ruby on Rails. These steps are also available in individual release guides.
After reading this guide, you will know:
--------------------------------------------------------------------------------
General Advice
@ -45,7 +47,7 @@ Rails 4.0 has removed the identity map from Active Record, due to [some inconsis
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 [Active Record Query guide](active_record_querying.html#ordering) for more information.
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`.
@ -69,14 +71,14 @@ in the `config/initializers/wrap_parameters.rb` file:
### Action Pack
There is an upgrading cookie store UpgradeSignatureToEncryptionCookieStore which helps you upgrading apps that use +CookieStore+ to the new default +EncryptedCookieStore+. To use this CookieStore set Myapp::Application.config.session_store :upgrade_signature_to_encryption_cookie_store, key: '_myapp_session' in your config/initializers/session_store.rb. You will also need to add Myapp::Application.config.secret_key_base = 'some secret' in your config/initializers/secret_token.rb, but do not remove +Myapp::Application.config.secret_token = 'some secret'+
There is an upgrading cookie store `UpgradeSignatureToEncryptionCookieStore` which helps you upgrading apps that use `CookieStore` to the new default `EncryptedCookieStore`. To use this CookieStore set `Myapp::Application.config.session_store :upgrade_signature_to_encryption_cookie_store, key: '_myapp_session'` in `config/initializers/session_store.rb`. Additionally, add `Myapp::Application.config.secret_key_base = 'some secret'` in config/initializers/secret_token.rb (use `rake secret` to generate a value). Do not remove `Myapp::Application.config.secret_token = 'some secret'`.
Rails 4.0 removed the `ActionController::Base.asset_path` option. Use the assets pipeline feature.
Rails 4.0 has deprecated `ActionController::Base.page_cache_extension` option. Use
`ActionController::Base.default_static_extension` instead.
Rails 4.0 has removed Action and Page caching from ActionPack. You will need to
Rails 4.0 has removed Action and Page caching from Action Pack. You will need to
add the `actionpack-action_caching` gem in order to use `caches_action` and
the `actionpack-page_caching` to use `caches_pages` in your controllers.

View File

@ -3,13 +3,15 @@ Working with JavaScript in Rails
This guide covers the built-in Ajax/JavaScript functionality of Rails (and
more); it will enable you to create rich and dynamic Ajax applications with
ease! We will cover the following topics:
ease!
* Quick introduction to Ajax
* Unobtrusive JavaScript
* How Rails' built-in helpers assist you
* Handling Ajax on the server side
* The Turbolinks gem
After reading this guide, you will know:
* Quick introduction to Ajax.
* Unobtrusive JavaScript.
* How Rails' built-in helpers assist you.
* Handling Ajax on the server side.
* The Turbolinks gem.
-------------------------------------------------------------------------------