From b047929c14f088d535eea460ddd8769f43cd4ae5 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sun, 2 Nov 2008 04:02:40 +0530 Subject: Merge with docrails --- railties/doc/guides/html/2_2_release_notes.html | 68 ++- .../doc/guides/html/actioncontroller_basics.html | 1 - railties/doc/guides/html/association_basics.html | 10 +- railties/doc/guides/html/finders.html | 653 +++++++++++---------- .../guides/html/getting_started_with_rails.html | 5 + railties/doc/guides/html/index.html | 16 - .../doc/guides/html/layouts_and_rendering.html | 158 +++-- railties/doc/guides/html/routing_outside_in.html | 2 +- railties/doc/guides/html/security.html | 14 + 9 files changed, 526 insertions(+), 401 deletions(-) (limited to 'railties/doc/guides/html') diff --git a/railties/doc/guides/html/2_2_release_notes.html b/railties/doc/guides/html/2_2_release_notes.html index 7e975d35a6..c68f10ad5a 100644 --- a/railties/doc/guides/html/2_2_release_notes.html +++ b/railties/doc/guides/html/2_2_release_notes.html @@ -337,72 +337,72 @@ More information :
@@ -612,7 +612,7 @@ More information:

5.4. New Dynamic Finders

Two new sets of methods have been added to Active Record's dynamic finders family.

-

5.4.1. find_last_by_<attributes>

+

5.4.1. find_last_by_<attribute>

The find_last_by_<attribute> method is equivalent to Model.last(:conditions ⇒ {:attribute ⇒ value})

by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite --> -
class Vendor << ActiveRecord::Base
+
class Vendor < ActiveRecord::Base
   has_one :account
   delegate :email, :password, :to => :account, :prefix => true
 end
 
-

This will produce delegated methods vendor.account_email and vendor.account_password. You can also specify a custom prefix:

+

This will produce delegated methods vendor#account_email and vendor#account_password. You can also specify a custom prefix:

-
class Vendor << ActiveRecord::Base
+
class Vendor < ActiveRecord::Base
   has_one :account
   delegate :email, :password, :to => :account, :prefix => :owner
 end
 
-

This will produce delegated methods vendor.owner_email and vendor.owner_password.

+

This will produce delegated methods vendor#owner_email and vendor#owner_password.

Lead Contributor: Daniel Schierbeck

9.4. Other Active Support Changes

    @@ -953,6 +963,11 @@ The addition of ActiveSupport::Rescuable allows any class to mix in the The included TzInfo library has been upgraded to version 0.3.11.

    +
  • +

    +ActiveSuport::StringInquirer gives you a pretty way to test for equality in strings: ActiveSupport::StringInquirer.new("abc").abc? ⇒ true +

    +

10. Railties

@@ -997,7 +1012,7 @@ The included TzInfo library has been upgraded to version 0.3.11.

-

You can unpack or install a single gem by specifying GEM=_gem_name on the command line.

+

You can unpack or install a single gem by specifying GEM=gem_name on the command line.

@@ -1046,7 +1066,7 @@ Instructions for setting up a continuous integration server to build Rails itsel
  • -Wrapped Rails.env in StringQuestioneer so you can do Rails.env.development? +Wrapped Rails.env in StringInquirer so you can do Rails.env.development?

  • diff --git a/railties/doc/guides/html/actioncontroller_basics.html b/railties/doc/guides/html/actioncontroller_basics.html index 2809034e27..32ddbe1f60 100644 --- a/railties/doc/guides/html/actioncontroller_basics.html +++ b/railties/doc/guides/html/actioncontroller_basics.html @@ -693,7 +693,6 @@ http://www.gnu.org/software/src-highlite -->

    Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The :only option is used to only skip this filter for these actions, and there is also an :except option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.

    6.1. After filters and around filters

    In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.

    -

    TODO: Find a real example for an around filter

    belongs_to :manager, :class_name => "User" end
    -

    With this setup, you can retrieve @employee.subordinates and @employee.managers.

    +

    With this setup, you can retrieve @employee.subordinates and @employee.manager.

    3. Tips, Tricks, and Warnings

    @@ -1185,6 +1185,14 @@ http://www.gnu.org/software/src-highlite -->

    If you set the :readonly option to true, then the associated object will be read-only when retrieved via the association.

    :select

    The :select option lets you override the SQL SELECT clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.

    +
    + + + +
    +Tip +If you set the :select option on a belongs_to association, you should also set the foreign_key option to guarantee the correct results.
    +
    :validate

    If you set the :validate option to true, then associated objects will be validated whenever you save this object. By default, this is false: associated objects will not be validated when this object is saved.

    4.1.3. When are Objects Saved?

    diff --git a/railties/doc/guides/html/finders.html b/railties/doc/guides/html/finders.html index b10d390105..f8396bb517 100644 --- a/railties/doc/guides/html/finders.html +++ b/railties/doc/guides/html/finders.html @@ -202,7 +202,7 @@ ul#navMain { In the beginning…
  • - Our Models + The Sample Models
  • Database Agnostic @@ -212,6 +212,15 @@ ul#navMain {
  • Conditions +
  • Ordering @@ -244,13 +253,16 @@ ul#navMain { Finding By SQL
  • + select_all +
  • +
  • Working with Associations
  • Named Scopes
  • - Existance of Objects + Existence of Objects
  • Calculations @@ -272,24 +284,7 @@ ul#navMain { Credits
  • - Change Log - + Changelog
  • @@ -298,14 +293,14 @@ ul#navMain {

    Rails Finders

    -

    This guide is all about the find method defined in ActiveRecord::Base, finding on associations, and associated goodness such as named scopes. You will learn how to be a find master.

    +

    This guide is all about the find method defined in ActiveRecord::Base, finding on associations, and associated goodness such as named scopes. You will learn how to be a find master.

    1. In the beginning…

    In the beginning there was SQL. SQL looked like this:

    -
    -
    @@ -314,13 +309,13 @@ http://www.gnu.org/software/src-highlite --> SELECT * FROM clients LIMIT 0,1 SELECT * FROM clients ORDER BY id DESC LIMIT 0,1
    -

    In Rails you don't usually have to type SQL (unlike other languages) because ActiveRecord is there to help you find your records.

    +

    In Rails (unlike some other frameworks) you don't usually have to type SQL because Active Record is there to help you find your records.

    -

    2. Our Models

    +

    2. The Sample Models

    -

    For this guide we have the following models:

    -
    -
    @@ -330,82 +325,78 @@ http://www.gnu.org/software/src-highlite --> has_many :orders has_and_belongs_to_many :roles end -
    -
    -
    -
    class Address < ActiveRecord::Base
    +
    +class Address < ActiveRecord::Base
       belongs_to :client
     end
    -
    -
    -
    -
    class MailingAddress < Address
    +
    +class MailingAddress < Address
     end
    -
    -
    -
    -
    class Order < ActiveRecord::Base
    +
    +class Order < ActiveRecord::Base
       belongs_to :client, :counter_cache => true
     end
    -
    -
    -
    -
    class Role < ActiveRecord::Base
    +
    +class Role < ActiveRecord::Base
       has_and_belongs_to_many :clients
     end
     

    3. Database Agnostic

    -

    ActiveRecord will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the ActiveRecord method format will always be the same.

    +

    Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the Active Record method format will always be the same.

    4. IDs, First, Last and All

    -

    ActiveRecord::Base has methods defined on it to make interacting with your database and the tables within it much, much easier: find. This method allows you to pass arguments into it to perform certain queries on your database without the need of SQL. If you wanted to find the record with the id of 1, you could type Client.find(1) which would execute this query on your database:

    -
    -
    -
    SELECT * FROM `clients` WHERE (`clients`.`id` = 1)
    -NOTE: Please be aware that because this is a standard table created from a migration in Rails that the primary key is defaulted to 'id'. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column.
    +
    SELECT * FROM +clients+ WHERE (+clients+.+id+ = 1)
     
    +
    + + + +
    +Note +Because this is a standard table created from a migration in Rail, the primary key is defaulted to id. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column.
    +

    If you wanted to find clients with id 1 or 2, you call Client.find([1,2]) or Client.find(1,2) and then this will be executed as:

    -
    -
    -
    SELECT * FROM `clients` WHERE (`clients`.`id` IN (1,2))
    -[source,txt]
    ->> Client.find(1,2)
    -=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2, created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">, #<Client id: 2, name: => "Michael", locked: false, orders_count: 3, created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
    +
    SELECT * FROM +clients+ WHERE (+clients+.+id+ IN (1,2))
     
    -

    Note that if you pass in a list of numbers that the result will be returned as an array, not an object of Client.

    -

    If you wanted to find the first client you would simply type Client.find(:first) and that would find the first client created in your clients table:

    -
    -
    -
    >> Client.find(:first)
    -=> #<Client id: 1, name: => "Ryan", locked: false, orders_count: 2, created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">
    -If you were running script/server you may see the following output:
    +
    >> Client.find(1,2)
    +=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
    +  created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
    +  #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
    +  created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
     
    -
    -
    +
    >> Client.first
    +=> #<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
    +  created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">
    +
    +

    If you were running script/server you might see the following output:

    +
    +
    @@ -413,142 +404,186 @@ http://www.gnu.org/software/src-highlite -->

    Indicating the query that Rails has performed on your database.

    To find the last client you would simply type Client.find(:last) and that would find the last client created in your clients table:

    -
    -
    >> Client.find(:last)
    -=> #<Client id: 2, name: => "Michael", locked: false, orders_count: 3, created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">
    +=> #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
    +  created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">
     
    -
    -
    SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
     
    -

    To find all the clients you would simply type Client.find(:all) and that would find all the clients in your clients table:

    -
    -
    -
    >> Client.find(:all)
    -=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2, created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">, #<Client id: 2, name: => "Michael", locked: false, orders_count: 3, created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
    +
    >> Client.all
    +=> [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
    +  created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
    +  #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
    +  created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
     
    -

    Alternatively to calling Client.find(:first)/Client.find(:last)/Client.find(:all), you could use the class method of Client.first/Client.last/Client.all instead. Client.first, Client.last and Client.all just call their longer counterparts.

    +

    As alternatives to calling Client.first, Client.last, and Client.all, you can use the class methods Client.first, Client.last, and Client.all instead. Client.first, Client.last and Client.all just call their longer counterparts: Client.find(:first), Client.find(:last) and Client.find(:all) respectively.

    Be aware that Client.first/Client.find(:first) and Client.last/Client.find(:last) will both return a single object, where as Client.all/Client.find(:all) will return an array of Client objects, just as passing in an array of ids to find will do also.

    5. Conditions

    -

    If you'd like to add conditions to your find, you could just specify them in there, just like Client.find(:first, :conditions ⇒ "orders_count = 2"). Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like Client.find(:first, :conditions ⇒ ["orders_count = ?", params[:orders]]). ActiveRecord will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like Client.find(:first, :conditions ⇒ ["orders_count = ? AND locked = ?", params[:orders], false]). In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has 2 as its value for the orders_count field and false for its locked field.

    +

    5.1. Pure String Conditions

    +

    If you'd like to add conditions to your find, you could just specify them in there, just like Client.first(:conditions ⇒ "orders_count = 2"). This will find all clients where the orders_count field's value is 2.

    +

    5.2. Array Conditions

    +
    +
    +
    Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.
    +

    The reason for doing code like:

    -
    -
    -
    `Client.find(:first, :conditions => ["orders_count = ?", params[:orders]])`
    +
    +Client.first(:conditions => ["orders_count = ?", params[:orders]])+
     

    instead of:

    -

    Client.find(:first, :conditions ⇒ "orders_count = #{params[:orders]}")

    -

    is because of parameter safety. Putting the variable directly into the conditions string will parse the variable as-is. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your parameters directly inside the conditions string.

    -

    If you're looking for a range inside of a table for example users created in a certain timeframe you can use the conditions option coupled with the IN sql statement for this. If we had two dates coming in from a controller we could do something like this to look for a range:

    -
    -
    -
    Client.find(:all, :conditions => ["created_at IN (?)", (params[:start_date].to_date)..(params[:end_date].to_date)])
    +
    Client.all(:conditions => ["created_at IN (?)",
    +  (params[:start_date].to_date)..(params[:end_date].to_date)])
     

    This would generate the proper query which is great for small ranges but not so good for larger ranges. For example if you pass in a range of date objects spanning a year that's 365 (or possibly 366, depending on the year) strings it will attempt to match your field against.

    -
    -
    -
    SELECT * FROM `users` WHERE (created_at IN ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05','2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11','2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17','2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',...
    -2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20','2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26','2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31'))
    +
    SELECT * FROM +users+ WHERE (created_at IN
    +  ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05',
    +  '2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11',
    +  '2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17',
    +  '2008-01-18','2008-01-19','2008-01-20','2008-01-21','2008-01-22','2008-01-23',...
    +  ‘2008-12-15','2008-12-16','2008-12-17','2008-12-18','2008-12-19','2008-12-20',
    +  '2008-12-21','2008-12-22','2008-12-23','2008-12-24','2008-12-25','2008-12-26',
    +  '2008-12-27','2008-12-28','2008-12-29','2008-12-30','2008-12-31'))
     

    Things can get really messy if you pass in time objects as it will attempt to compare your field to every second in that range:

    -
    -
    -
    Client.find(:all, :conditions => ["created_at IN (?)", (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)])
    +
    Client.all(:conditions => ["created_at IN (?)",
    +  (params[:start_date].to_date.to_time)..(params[:end_date].to_date.to_time)])
     
    -
    -
    -
    SELECT * FROM `users` WHERE (created_at IN ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ... '2007-12-01 23:59:59', '2007-12-02 00:00:00'))
    +
    SELECT * FROM +users+ WHERE (created_at IN
    +  ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ...
    +  '2007-12-01 23:59:59', '2007-12-02 00:00:00'))
     

    This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:

    -
    -
    -
    Got a packet bigger than 'max_allowed_packet' bytes: <query>
    +
    Got a packet bigger than 'max_allowed_packet' bytes: _query_
     
    -

    Where <query> is the actual query used to get that error.

    +

    Where query is the actual query used to get that error.

    In this example it would be better to use greater-than and less-than operators in SQL, like so:

    -
    -
    -
    Client.find(:all, :condtions => ["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]])
    +
    Client.all(:conditions =>
    +  ["created_at > ? AND created_at < ?", params[:start_date], params[:end_date]])
     

    You can also use the greater-than-or-equal-to and less-than-or-equal-to like this:

    -
    -
    -
    Client.find(:all, :condtions => ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
    +
    Client.all(:conditions =>
    +  ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])
     

    Just like in Ruby.

    +

    5.3. Hash Conditions

    +

    Similar to the array style of params you can also specify keys in your conditions:

    +
    +
    +
    Client.all(:conditions =>
    +  ["created_at >= :start_date AND created_at <= :end_date", { :start_date => params[:start_date], :end_date => params[:end_date] }])
    +
    +

    This makes for clearer readability if you have a large number of variable conditions.

    6. Ordering

    -

    If you're getting a set of records and want to force an order, you can use Client.find(:all, :order ⇒ "created_at") which by default will sort the records by ascending order. If you'd like to order it in descending order, just tell it to do that using Client.find(:all, :order ⇒ "created_at desc")

    +

    If you're getting a set of records and want to force an order, you can use Client.all(:order ⇒ "created_at") which by default will sort the records by ascending order. If you'd like to order it in descending order, just tell it to do that using Client.all(:order ⇒ "created_at desc")

    7. Selecting Certain Fields

    -

    To select certain fields, you can use the select option like this: Client.find(:first, :select ⇒ "viewable_by, locked"). This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute SELECT viewable_by, locked FROM clients LIMIT 0,1 on your database.

    +

    To select certain fields, you can use the select option like this: Client.first(:select ⇒ "viewable_by, locked"). This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute SELECT viewable_by, locked FROM clients LIMIT 0,1 on your database.

    8. Limit & Offset

    If you want to limit the amount of records to a certain subset of all the records retreived you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retreived from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:

    -
    -
    -
    Client.find(:all, :limit => 5)
    +
    Client.all(:limit => 5)
     
    -

    This code will return a maximum of 5 clients and because we've specified no offset it will return the first 5 clients in the table. The SQL it executes will look like this:

    -
    -
    SELECT * FROM clients LIMIT 5
     
    -
    -
    -
    Client.find(:all, :limit => 5, :offset => 5)
    +
    Client.all(:limit => 5, :offset => 5)
     
    -

    This code will return a maximum of 5 clients and because we have specified an offset this time, it will return these records starting from the 5th client in the clients table. The SQL looks like:

    -
    -
    @@ -557,50 +592,50 @@ http://www.gnu.org/software/src-highlite -->

    9. Group

    -

    The group option for find is useful, for example, if you want to find a collection of the dates orders were created on. We could use the option in this context:

    -
    -
    -
    Order.find(:all, :group => "date(created_at)", :order => "created_at")
    +
    Order.all(:group => "date(created_at)", :order => "created_at")
     
    -

    And this will give us a single Order object for each date that we have orders in our database.

    +

    And this will give you a single Order object for each date where there are orders in the database.

    The SQL that would be executed would be something like this:

    -
    -
    -
    SELECT * FROM `orders` GROUP BY date(created_at)
    +
    SELECT * FROM +orders+ GROUP BY date(created_at)
     

    10. Read Only

    -

    Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an ActiveRecord::ReadOnlyRecord error. To set this option, specify it like this:

    -
    -
    -
    Client.find(:first, :readonly => true)
    +
    Client.first(:readonly => true)
     
    -

    If you assign this record to a variable client calling the following code will raise an ActiveRecord::ReadOnlyRecord:

    -
    -
    -
    client = Client.find(:first, :readonly => true)
    +
    client = Client.first(:readonly => true)
     client.locked = false
     client.save
     

    11. Lock

    -

    If you're wanting to stop race conditions for a specific record, say for example you're incrementing a single field for a record you can use the lock option to ensure that the record is updated correctly. It's recommended this be used inside a transaction.

    -
    -
    @@ -612,56 +647,71 @@ http://www.gnu.org/software/src-highlite -->

    12. Making It All Work Together

    -

    You can chain these options together in no particular order as ActiveRecord will write the correct SQL for you. If you specify two instances of the same options inside the find statement ActiveRecord will use the latter.

    +

    You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement ActiveRecord will use the latter.

    13. Eager Loading

    -

    Eager loading is loading associated records along with any number of records in as few queries as possible. Lets say for example if we wanted to load all the addresses associated with all the clients all in the same query we would use Client.find(:all, :include ⇒ :address). If we wanted to include both the address and mailing address for the client we would use `Client.find(:all), :include ⇒ [:address, :mailing_address]). Inclue will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:

    -
    -
    Client Load (0.000383)   SELECT * FROM clients
    -Address Load (0.119770)   SELECT addresses.* FROM addresses WHERE (addresses.client_id IN (13,14))
    -MailingAddress Load (0.001985) SELECT mailing_addresses.* FROM mailing_addresses WHERE (mailing_addresses.client_id IN (13,14))
    +Address Load (0.119770)   SELECT addresses.* FROM addresses
    +  WHERE (addresses.client_id IN (13,14))
    +MailingAddress Load (0.001985) SELECT mailing_addresses.* FROM
    +  mailing_addresses WHERE (mailing_addresses.client_id IN (13,14))
    +
    +

    The numbers 13 and 14 in the above SQL are the ids of the clients gathered from the Client.all query. Rails will then run a query to gather all the addresses and mailing addresses that have a client_id of 13 or 14. Although this is done in 3 queries, this is more efficient than not eager loading because without eager loading it would run a query for every time you called address or mailing_address on one of the objects in the clients array, which may lead to performance issues if you're loading a large number of records at once.

    +

    If you wanted to get all the addresses for a client in the same query you would do Client.all(:joins ⇒ :address) and you wanted to find the address and mailing address for that client you would do Client.all(:joins ⇒ [:address, :mailing_address]). This is more efficient because it does all the SQL in one query, as shown by this example:

    +
    +
    +
    +Client Load (0.000455)   SELECT clients.* FROM clients INNER JOIN addresses
    +  ON addresses.client_id = client.id INNER JOIN mailing_addresses ON
    +  mailing_addresses.client_id = client.id
     
    -

    The numbers 13 and 14 in the above SQL are the ids of the clients gathered from the Client.find(:all) query. Rails will then run a query to gather all the addresses and mailing addresses that have a client_id of 13 or 14. Although this is done in 3 queries, this is more efficient than not eager loading because without eager loading it would run a query for every time you called address or mailing_address on one of the objects in the clients array, which may lead to performance issues if you're loading a large number of records at once.

    -

    An alternative (and more efficient) way to do eager loading is to use the joins option. For example if we wanted to get all the addresses for a client we would do Client.find(:all, :joins ⇒ :address) and if we wanted to find the address and mailing address for that client we would do Client.find(:all, :joins ⇒ [:address, :mailing_address]). This is more efficient because it does all the SQL in one query, as shown by this example:

    -
    -
    -
    `Client Load (0.000455)   SELECT clients.* FROM clients INNER JOIN addresses ON addresses.client_id = client.id INNER JOIN mailing_addresses ON mailing_addresses.client_id = client.id
    +
    Client.all(:joins => “LEFT OUTER JOIN addresses ON
    +  client.id = addresses.client_id LEFT OUTER JOIN mailing_addresses ON
    +  client.id = mailing_addresses.client_id”)
     
    -

    This query is more efficent, but there's a gotcha. If you have a client who does not have an address or a mailing address they will not be returned in this query at all. If you have any association as an optional association, you may want to use include rather than joins.

    When using eager loading you can specify conditions for the columns of the tables inside the eager loading to get back a smaller subset. If, for example, you want to find a client and all their orders within the last two weeks you could use eager loading with conditions for this:

    -
    -
    -
    Client.find(:first, :include => "orders", :conditions => ["orders.created_at >= ? AND orders.created_at <= ?", Time.now - 2.weeks, Time.now])
    +
    Client.first(:include => "orders", :conditions =>
    +  ["orders.created_at >= ? AND orders.created_at <= ?", Time.now - 2.weeks, Time.now])
     

    14. Dynamic finders

    -

    With every field (also known as an attribute) you define in your table, ActiveRecord provides finder methods for these. If you have a field called name on your Client model for example, you get find_by_name and find_all_by_name for free from ActiveRecord. If you have also have a locked field on the client model, you also get find_by_locked and find_all_by_locked. 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_name_and_locked(Ryan, true). These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type find_by_name(params[:name]) than it is to type find(:first, :conditions ⇒ ["name = ?", params[:name]]).

    -

    There's another set of dynamic finders that let you find or create/initialize objects if they aren't find. These work in a similar fashion to the other finders and can be used like find_or_create_by_name(params[:name]). Using this will firstly perform a find and then create if the find returns nil, the SQL looks like this for Client.find_or_create_by_name(Ryan):

    -
    -
    -
    SELECT * FROM `clients` WHERE (`clients`.`name` = 'Ryan') LIMIT 1
    +
    SELECT * FROM +clients+ WHERE (+clients+.+name+ = 'Ryan') LIMIT 1
     BEGIN
    -INSERT INTO `clients` (`name`, `updated_at`, `created_at`, `orders_count`, `locked`) VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', '0', '0')
    +INSERT INTO +clients+ (+name+, +updated_at+, +created_at+, +orders_count+, +locked+)
    +  VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', '0', '0')
     COMMIT
     
    -

    find_or_create's sibling, find_or_initialize, will find an object and if it does not exist will call new with the parameters you passed in. For example:

    -
    -
    @@ -671,25 +721,36 @@ http://www.gnu.org/software/src-highlite -->

    15. Finding By SQL

    -

    If you'd like to use your own SQL to find records a table you can use find_by_sql. find_by_sql will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query:

    -
    -
    Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
     
    -

    find_by_sql provides you with a simple way of making custom calls to the database and converting those to objects.

    +

    find_by_sql provides you with a simple way of making custom calls to the database and retreiving instantiated objects.

    +
    +

    16. select_all

    +
    +

    find_by_sql has a close relative called select_all. select_all will retreive 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.

    +
    +
    +
    Client.connection.select_all("SELECT * FROM `clients` WHERE `id` = '1'")
    +
    -

    16. Working with Associations

    +

    17. Working with Associations

    When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an exisiting record, for example finding all the orders for a client that have been sent and not received by doing something like Client.find(params[:id]).orders.find_by_sent_and_received(true, false). Having this find method available on associations is extremely helpful when using nested controllers.

    -

    17. Named Scopes

    +

    18. Named Scopes

    -

    In this section we'll cover adding named scopes to the models in the application. Let's say we want to find all clients who are male we would use this code:

    -
    -
    @@ -697,10 +758,10 @@ http://www.gnu.org/software/src-highlite --> named_scope :males, :conditions => { :gender => "male" } end
    -

    And we could call it like Client.males to get all the clients who are male.

    -

    If we wanted to find all the clients who are active, we could use this:

    -
    -
    @@ -708,26 +769,26 @@ http://www.gnu.org/software/src-highlite --> named_scope :active, :conditions => { :active => true } end
    -

    We would call this new named_scope by doing Client.active and this will do the same query as if we just used Client.find(:all, :conditions ⇒ ["active = ?", true]). Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do Client.active.first.

    -

    and then if we wanted to find all the clients who are active and male we could stack the named scopes like this:

    -
    -
    -
    Client.males.active
    +
    Client.males.active.all
     
    -

    If you would then like to do a find on that subset of clients, you can. Just like an association, named scopes allow you to call find on a set of records:

    -
    -
    -
    Client.males.active.find(:all, :conditions => ["age > ?", params[:age]])
    +
    Client.males.active.all(:conditions => ["age > ?", params[:age]])
     
    -

    Now observe the following code:

    -
    -
    @@ -735,9 +796,9 @@ http://www.gnu.org/software/src-highlite --> named_scope :recent, :conditions => { :created_at > 2.weeks.ago } end
    -

    What we see here is what looks to be a standard named scope that defines a method called recent which gathers all records created any time between now and 2 weeks ago. That's correct for the first time the model is loaded but for any time after that, 2.weeks.ago is set to that same value, so you will consistently get records from a certain date until your model is reloaded by something like your application restarting. The way to fix this is to put the code in a lambda block:

    -
    -
    @@ -745,54 +806,67 @@ http://www.gnu.org/software/src-highlite --> named_scope :recent, lambda { { :conditions => ["created_at > ?", 2.weeks.ago] } } end
    -

    And now every time the recent named scope is called, because it's wrapped in a lambda block this code will be parsed every time so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.

    +

    And now every time the recent named scope is called, the code in the lambda block will be parsed, so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.

    In a named scope you can use :include and :joins options just like in find.

    -
    -
    class Client < ActiveRecord::Base
    -  named_scope :active_within_2_weeks, :joins => :order, lambda { { :conditions => ["orders.created_at > ?", 2.weeks.ago] } }
    +  named_scope :active_within_2_weeks, :joins => :order,
    +    lambda { { :conditions => ["orders.created_at > ?", 2.weeks.ago] } }
     end
     
    -

    This method called as Client.active_within_2_weeks will return all clients who have placed orders in the past 2 weeks.

    +

    This method, called as Client.active_within_2_weeks.all, will return all clients who have placed orders in the past 2 weeks.

    If you want to pass a named scope a compulsory argument, just specify it as a block parameter like this:

    -
    -
    +
    class Client < ActiveRecord::Base
    +  named_scope :recent, lambda { |time| { :conditions => ["created_at > ?", time] } }
    +end
    +
    +

    This will work if you call Client.recent(2.weeks.ago).all but not if you call Client.recent. If you want to add an optional argument for this, you have to use the splat operator as the block's parameter.

    +
    +
    class Client < ActiveRecord::Base
    -  named_scope :recent, lambda { |time| { :conditions => ["created_at > ?", time] } } }
    +  named_scope :recent, lambda { |*args| { :conditions => ["created_at > ?", args.first || 2.weeks.ago] } }
     end
     
    -

    This will work if we call Client.recent(2.weeks.ago) but not if we call Client.recent. If we want to add an optional argument for this, we have to use the splat operator as the block's parameter.

    -
    -
    class Client < ActiveRecord::Base
    -  named_scope :recent, lambda { |*args| { :conditions => ["created_at > ?", args.first || 2.weeks.ago] } } }
    +  def self.recent
    +    scoped :conditions => ["created_at > ?", 2.weeks.ago]
    +  end
     end
     
    -

    This will work with Client.recent(2.weeks.ago) and Client.recent with the latter always returning records with a created_at date between right now and 2 weeks ago.

    -

    Remember that named scopes are stackable, so you will be able to do Client.recent(2.weeks.ago).unlocked to find all clients created between right now and 2 weeks ago and have their locked field set to false.

    -

    18. Existance of Objects

    +

    19. Existence of Objects

    -

    If you simply want to check for the existance of the object there's a method called exists?. This method will query the database using the same query as find, but instead of returning an object or collection of objects it will return either true or false.

    -
    -
    Client.exists?(1)
     

    The above code will check for the existance of a clients table record with the id of 1 and return true if it exists.

    -
    -
    @@ -800,90 +874,92 @@ http://www.gnu.org/software/src-highlite --> # or Client.exists?([1,2,3])
    -

    exists? also takes multiple ids, as shown by the above code, but the catch is that it will return true if any one of those records exists.

    +

    The exists? method also takes multiple ids, as shown by the above code, but the catch is that it will return true if any one of those records exists.

    Further more, exists takes a conditions option much like find:

    -
    -
    Client.exists?(:conditions => "first_name = 'Ryan'")
     
    -

    19. Calculations

    +

    20. Calculations

    This section uses count as an example method in this preamble, but the options described apply to all sub-sections.

    count takes conditions much in the same way exists? does:

    -
    -
    Client.count(:conditions => "first_name = 'Ryan'")
     

    Which will execute:

    -
    -
    -
    SELECT count(*) AS count_all FROM `clients` WHERE (first_name = 1)
    +
    SELECT count(*) AS count_all FROM +clients+ WHERE (first_name = 1)
     

    You can also use include or joins for this to do something a little more complex:

    -
    -
    Client.count(:conditions => "clients.first_name = 'Ryan' AND orders.status = 'received'", :include => "orders")
     

    Which will execute:

    -
    -
    -
    SELECT count(DISTINCT `clients`.id) AS count_all FROM `clients` LEFT OUTER JOIN `orders` ON orders.client_id = client.id WHERE (clients.first_name = 'name' AND orders.status = 'received')
    +
    SELECT count(DISTINCT +clients+.id) AS count_all FROM +clients+
    +  LEFT OUTER JOIN +orders+ ON orders.client_id = client.id WHERE
    +  (clients.first_name = 'name' AND orders.status = 'received')
     
    -

    We specify clients.first_name just in case one of our join tables has a field also called first_name and we do orders.status because that's the name of our join table.

    -

    19.1. Count

    +

    This code specifies clients.first_name just in case one of the join tables has a field also called first_name and it uses orders.status because that's the name of our join table.

    +

    20.1. Count

    If you want to see how many records are in your model's table you could call Client.count and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use Client.count(:age).

    For options, please see the parent section, Calculations.

    -

    19.2. Average

    +

    20.2. Average

    If you want to see the average of a certain number in one of your tables you can call the average method on the class that relates to the table. This method call will look something like this:

    -
    -
    Client.average("orders_count")
     
    -

    This will return a number (possibly a floating point number such as 3.14159265) representing the average of the fields.

    +

    This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.

    For options, please see the parent section, Calculations

    -

    19.3. Minimum

    +

    20.3. Minimum

    If you want to find the minimum value of a field in your table you can call the minimum method on the class that relates to the table. This method call will look something like this:

    -
    -
    Client.minimum("age")
     

    For options, please see the parent section, Calculations

    -

    19.4. Maximum

    +

    20.4. Maximum

    If you want to find the maximum value of a field in your table you can call the maximum method on the class that relates to the table. This method call will look something like this:

    -
    -
    Client.maximum("age")
     

    For options, please see the parent section, Calculations

    -

    19.5. Sum

    +

    20.5. Sum

    If you want to find the sum of a field for all records in your table you can call the sum method on the class that relates to the table. This method call will look something like this:

    -
    -
    @@ -891,109 +967,66 @@ http://www.gnu.org/software/src-highlite -->

    For options, please see the parent section, Calculations

    -

    20. Credits

    +

    21. Credits

    Thanks to Ryan Bates for his awesome screencast on named scope #108. The information within the named scope section is intentionally similar to it, and without the cast may have not been possible.

    Thanks to Mike Gunderloy for his tips on creating this guide.

    -

    21. Change Log

    +

    22. Changelog

    -

    21.1. Sunday, 28 September 2008

    -
      -
    1. -

      -Changed "In Rails you don't have to type SQL" to "In Rails you don't usually have to type SQL" -

      -
    2. -
    3. -

      -Inserted paragraph in dynamic finders about find_or_create and find_or_initialize -

      -
    4. -
    5. -

      -Extended "First, Last, All" section. -

      -
    6. -
    7. -

      -Renamed "First, Last & All" to "IDs, First, Last and All" -

      -
    8. -
    9. -

      -Added finding by id and passing in ids to "IDs, First, Last and All" -

      -
    10. -
    -

    21.2. Wednesday, 01 October 2008

    -
      + +
      • -Did section on limit and offset, as well as section on readonly. +October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section.

      • -Altered formatting so it doesn't look bad. +October 27, 2008: Fixed up all points specified in this comment with an exception of the final point.

      • -
    -

    21.3. Sunday, 05 October 2008

    -
    1. -Extended conditions section to include IN and using operators inside the conditions. +October 26, 2008: Editing pass by Mike Gunderloy . First release version.

    2. -Extended conditions section to include paragraph and example of parameter safety. +October 22, 2008: Calculations complete, first complete draft by Ryan Bigg

    3. -Added TODO sections. +October 21, 2008: Extended named scope section by Ryan Bigg

    4. -
    -

    21.4. Monday, 06 October 2008

    -
    1. -Added section in Eager Loading about using conditions on tables that are not the model's own. +October 9, 2008: Lock, count, cleanup by Ryan Bigg

    2. -
    -

    21.5. Thursday, 09 October 2008

    -
    1. -Wrote section about lock option and tidied up "Making it all work together" section. +October 6, 2008: Eager loading by Ryan Bigg

    2. -Added section on using count. +October 5, 2008: Covered conditions by Ryan Bigg

    3. -
    -

    21.6. Tuesday, 21 October 2008

    -
    1. -Extended named scope guide by adding :include and :joins and find sub-sections. +October 1, 2008: Covered limit/offset, formatting changes by Ryan Bigg

    2. -
    -

    21.7. Wednesday, 22 October 2008

    -
    1. -Completed calculations section. +September 28, 2008: Covered first/last/all by Ryan Bigg

    2. -
    +
    diff --git a/railties/doc/guides/html/getting_started_with_rails.html b/railties/doc/guides/html/getting_started_with_rails.html index d9a1779d56..797ae2fb3a 100644 --- a/railties/doc/guides/html/getting_started_with_rails.html +++ b/railties/doc/guides/html/getting_started_with_rails.html @@ -2010,6 +2010,11 @@ The Rails wiki
    • +November 1, 2008: First approved version by Mike Gunderloy +

      +
    • +
    • +

      October 16, 2008: Revised based on feedback from Pratik Naik by Mike Gunderloy (not yet approved for publication)

    • diff --git a/railties/doc/guides/html/index.html b/railties/doc/guides/html/index.html index f84442d10c..306257678b 100644 --- a/railties/doc/guides/html/index.html +++ b/railties/doc/guides/html/index.html @@ -219,14 +219,6 @@ ul#navMain {

      Models

      @@ -326,14 +318,6 @@ Enjoy.

    diff --git a/railties/doc/guides/html/layouts_and_rendering.html b/railties/doc/guides/html/layouts_and_rendering.html index a394da71df..1c9ef8ce24 100644 --- a/railties/doc/guides/html/layouts_and_rendering.html +++ b/railties/doc/guides/html/layouts_and_rendering.html @@ -489,7 +489,17 @@ http://www.gnu.org/software/src-highlite --> You don't need to call to_xml on the object that you want to render. If you use the :xml option, render will automatically call to_xml for you.
    -

    2.2.10. Options for render

    +

    2.2.10. Rendering Vanilla JavaScript

    +

    Rails can render vanilla JavaScript (as an alternative to using update with n .rjs file):

    +
    +
    +
    render :js => "alert('Hello Rails');"
    +
    +

    This will send the supplied string to the browser with a MIME type of text/javascript.

    +

    2.2.11. Options for render

    Calls to the render method generally accept four options:

    • @@ -560,7 +570,7 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
      render :xml => photo, :location => photo_url(photo)
       
    -

    2.2.11. Finding Layouts

    +

    2.2.12. Finding Layouts

    To find the current layout, Rails first looks for a file in app/views/layouts with the same base name as the controller. For example, rendering actions from the PhotosController class will use /app/views/layouts/photos.html.erb. If there is no such controller-specific layout, Rails will use /app/views/layouts/application.html.erb. If there is no .erb layout, Rails will use a .builder layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions.

    Specifying Layouts on a per-Controller Basis

    You can override the automatic layout conventions in your controllers by using the layout declaration in the controller. For example:

    @@ -632,6 +642,7 @@ end

    With those declarations, the inventory layout would be used only for the index method, the product layout would be used for everything else except the rss method, and the rss method will have its layout determined by the automatic layout rules.

    Layout Inheritance

    Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:

    +

    application.rb:

    layout "main" #... end - -class PostsController < ApplicationController +
    +

    posts_controller.rb:

    +
    +
    +
    class PostsController < ApplicationController
       # ...
     end
    -
    -class SpecialPostsController < PostsController
    +
    +

    special_posts_controller.rb:

    +
    +
    +
    class SpecialPostsController < PostsController
       layout "special"
       # ...
     end
    -
    -class OldPostsController < SpecialPostsController
    +
    +

    old_posts_controller.rb:

    +
    +
    +
    class OldPostsController < SpecialPostsController
       layout nil
     
       def show
    @@ -693,7 +722,7 @@ In general, views will be rendered in the main layout
     

    -

    2.2.12. Avoiding Double Render Errors

    +

    2.2.13. Avoiding Double Render Errors

    Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that render works.

    For example, here's some code that will trigger this error:

    @@ -933,7 +962,7 @@ http://www.gnu.org/software/src-highlite --> by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite --> -
    <%= javascript_include_tag :all, :recursive %>
    +
    <%= javascript_include_tag :all, :recursive => true %>
     

    If you're loading multiple javascript files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify :cache ⇒ true in your javascript_include_tag:

    @@ -1007,7 +1036,7 @@ http://www.gnu.org/software/src-highlite --> by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite --> -
    <%= stylesheet_link_tag :all, :recursive %>
    +
    <%= stylesheet_link_tag :all, :recursive => true %>
     

    If you're loading multiple CSS files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify :cache ⇒ true in your stylesheet_link_tag:

    @@ -1185,26 +1214,33 @@ http://www.gnu.org/software/src-highlite -->

    This would look for a partial named _link_area.html.erb and render it using the layout _graybar.html.erb. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master layouts folder).

    3.4.4. Passing Local Variables

    You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:

    +

    new.html.erb:

    -
    new.html.erb:
    -
    -<h1>New zone</h1>
    +
    <h1>New zone</h1>
     <%= error_messages_for :zone %>
     <%= render :partial => "form", :locals => { :button_label => "Create zone", :zone => @zone } %>
    -
    -edit.html.erb:
    -
    -<h1>Editing zone</h1>
    +
    +

    edit.html.erb:

    +
    +
    +
    <h1>Editing zone</h1>
     <%= error_messages_for :zone %>
     <%= render :partial => "form", :locals => { :button_label => "Update zone", :zone => @zone } %>
    -
    -_form.html.erb:
    -
    -<% form_for(@zone) do |f| %>
    +
    +

    _form.html.erb:

    +
    +
    +
    <% form_for(zone) do |f| %>
             <p>
               <b>Zone name</b><br />
               <%= f.text_field :name %>
    @@ -1215,7 +1251,7 @@ _form.html.erb:
     <% end %>
     

    Although the same partial will be rendered into both views, the label on the submit button is controlled by a local variable passed into the partial.

    -

    Every partial also has a local variable with the same name as the partial (minus the underscore). By default, it will look for an instance variable with the same name as the partial in the parent. You can pass an object in to this local variable via the :object option:

    +

    Every partial also has a local variable with the same name as the partial (minus the underscore). You can pass an object in to this local variable via the :object option:

    <%= render :partial => "customer", :object => @new_customer %>
     

    Within the customer partial, the @customer variable will refer to @new_customer from the parent view.

    +
    + + + +
    +Warning +In previous versions of Rails, the default local variable would look for an instance variable with the same name as the partial in the parent. This behavior is deprecated in Rails 2.2 and will be removed in a future version.
    +

    If you have an instance of a model to render into a partial, you can use a shorthand syntax:

    Assuming that the @customer instance variable contains an instance of the Customer model, this will use _customer.html.erb to render it.

    3.4.5. Rendering Collections

    Partials are very useful in rendering collections. When you pass a collection to a partial via the :collection option, the partial will be inserted once for each member in the collection:

    +

    index.html.erb:

    -
    index.html.erb:
    -
    -<h1>Products</h1>
    +
    <h1>Products</h1>
     <%= render :partial => "product", :collection => @products %>
    -
    -_product.html.erb:
    -
    -<p>Product Name: <%= product.name %></p>
    +
    +

    _product.html.erb:

    +
    +
    +
    <p>Product Name: <%= product.name %></p>
     

    When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is _product, and within the +_product partial, you can refer to product to get the instance that is being rendered. To use a custom local variable name within the partial, specify the :as option in the call to the partial:

    @@ -1268,38 +1315,48 @@ http://www.gnu.org/software/src-highlite -->

    Rails will render the _product_ruler partial (with no data passed in to it) between each pair of _product partials.

    There's also a shorthand syntax available for rendering collections. For example, if @products is a collection of products, you can render the collection this way:

    +

    index.html.erb:

    -
    index.html.erb:
    -
    -<h1>Products</h1>
    +
    <h1>Products</h1>
     <%= render :partial => @products %>
    -
    -_product.html.erb:
    -
    -<p>Product Name: <%= product.name %></p>
    +
    +

    _product.html.erb:

    +
    +
    +
    <p>Product Name: <%= product.name %></p>
     

    Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection:

    +

    index.html.erb:

    -
    index.html.erb:
    -
    -<h1>Contacts</h1>
    +
    <h1>Contacts</h1>
     <%= render :partial => [customer1, employee1, customer2, employee2] %>
    -
    -_customer.html.erb:
    -
    -<p>Name: <%= customer.name %></p>
    -
    -_employee.html.erb:
    -
    -<p>Name: <%= employee.name %></p>
    +
    +

    _customer.html.erb:

    +
    +
    +
    <p>Name: <%= customer.name %></p>
    +
    +

    _employee.html.erb:

    +
    +
    +
    <p>Name: <%= employee.name %></p>
     

    In this case, Rails will use the customer or employee partials as appropriate for each member of the collection.

    @@ -1309,6 +1366,11 @@ _employee.html.erb:
    • +November 1, 2008: Added :js option for render by Mike Gunderloy +

      +
    • +
    • +

      October 16, 2008: Ready for publication by Mike Gunderloy

    • diff --git a/railties/doc/guides/html/routing_outside_in.html b/railties/doc/guides/html/routing_outside_in.html index ca8958eef9..a1f1f98cfb 100644 --- a/railties/doc/guides/html/routing_outside_in.html +++ b/railties/doc/guides/html/routing_outside_in.html @@ -1756,7 +1756,7 @@ http://www.gnu.org/software/src-highlite --> :has_many => { :tags, :ratings} end
    -

    As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get admin_photos_url that expects to find an Admin::PhotosController and that matches admin/photos, and admin_photos_ratings+path that matches /admin/photos/photo_id/ratings, expecting to use Admin::RatingsController. Even though you're not specifying path_prefix explicitly, the routing code will calculate the appropriate path_prefix from the route nesting.

    +

    As you can see, the namespaced version is much more succinct than the one that spells everything out - but it still creates the same routes. For example, you'll get admin_photos_url that expects to find an Admin::PhotosController and that matches admin/photos, and admin_photos_ratings_path that matches /admin/photos/photo_id/ratings, expecting to use Admin::RatingsController. Even though you're not specifying path_prefix explicitly, the routing code will calculate the appropriate path_prefix from the route nesting.

    3.11. Adding More RESTful Actions

    You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional member routes (those which apply to a single instance of the resource), additional new routes (those that apply to creating a new resource), or additional collection routes (those which apply to the collection of resources as a whole).

    3.11.1. Adding Member Routes

    diff --git a/railties/doc/guides/html/security.html b/railties/doc/guides/html/security.html index a135d9b486..390efb5435 100644 --- a/railties/doc/guides/html/security.html +++ b/railties/doc/guides/html/security.html @@ -310,6 +310,9 @@ ul#navMain {
  • Additional resources
  • +
  • + Changelog +
  • @@ -1324,6 +1327,17 @@ Another good security blog with some Chea

    + +

    10. Changelog

    +
    + +
      +
    • +

      +November 1, 2008: First approved version by Heiko Webers +

      +
    • +
    -- cgit v1.2.3