Skip to content

Commit

Permalink
Merge branch 'master' of github.com:lifo/docrails
Browse files Browse the repository at this point in the history
  • Loading branch information
vijaydev committed Oct 14, 2011
2 parents 521a089 + e2a3952 commit e759c88
Show file tree
Hide file tree
Showing 13 changed files with 206 additions and 89 deletions.
4 changes: 2 additions & 2 deletions actionpack/lib/action_controller/metal/data_streaming.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ module DataStreaming
# If no content type is registered for the extension, default type 'application/octet-stream' will be used. # If no content type is registered for the extension, default type 'application/octet-stream' will be used.
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded. # * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
# Valid values are 'inline' and 'attachment' (default). # Valid values are 'inline' and 'attachment' (default).
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to '200 OK'. # * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
# * <tt>:url_based_filename</tt> - set to +true+ if you want the browser guess the filename from # * <tt>:url_based_filename</tt> - set to +true+ if you want the browser guess the filename from
# the URL, which is necessary for i18n filenames on certain browsers # the URL, which is necessary for i18n filenames on certain browsers
# (setting <tt>:filename</tt> overrides this option). # (setting <tt>:filename</tt> overrides this option).
Expand Down Expand Up @@ -92,7 +92,7 @@ def send_file(path, options = {}) #:doc:
# If no content type is registered for the extension, default type 'application/octet-stream' will be used. # If no content type is registered for the extension, default type 'application/octet-stream' will be used.
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded. # * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
# Valid values are 'inline' and 'attachment' (default). # Valid values are 'inline' and 'attachment' (default).
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to '200 OK'. # * <tt>:status</tt> - specifies the status code to send with the response. Defaults to 200.
# #
# Generic data download: # Generic data download:
# #
Expand Down
2 changes: 2 additions & 0 deletions actionpack/lib/action_controller/metal/head.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ module Head
# #
# head :created, :location => person_path(@person) # head :created, :location => person_path(@person)
# #
# head :created, :location => @person
#
# It can also be used to return exceptional conditions: # It can also be used to return exceptional conditions:
# #
# return head(:method_not_allowed) unless request.post? # return head(:method_not_allowed) unless request.post?
Expand Down
4 changes: 2 additions & 2 deletions activemodel/lib/active_model/validations/validates.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ module ClassMethods
# #
# class EmailValidator < ActiveModel::EachValidator # class EmailValidator < ActiveModel::EachValidator
# def validate_each(record, attribute, value) # def validate_each(record, attribute, value)
# record.errors[attribute] << (options[:message] || "is not an email") unless # record.errors.add attribute, (options[:message] || "is not an email") unless
# value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i # value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
# end # end
# end # end
Expand All @@ -48,7 +48,7 @@ module ClassMethods
# #
# class TitleValidator < ActiveModel::EachValidator # class TitleValidator < ActiveModel::EachValidator
# def validate_each(record, attribute, value) # def validate_each(record, attribute, value)
# record.errors[attribute] << "must start with 'the'" unless value =~ /\Athe/i # record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/i
# end # end
# end # end
# #
Expand Down
2 changes: 1 addition & 1 deletion activemodel/lib/active_model/validations/with.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ module ClassMethods
# class MyValidator < ActiveModel::Validator # class MyValidator < ActiveModel::Validator
# def validate(record) # def validate(record)
# if some_complex_logic # if some_complex_logic
# record.errors[:base] << "This record is invalid" # record.errors.add :base, "This record is invalid"
# end # end
# end # end
# #
Expand Down
6 changes: 3 additions & 3 deletions activemodel/lib/active_model/validator.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ module ActiveModel #:nodoc:
# #
# class MyValidator < ActiveModel::Validator # class MyValidator < ActiveModel::Validator
# def validate(record) # def validate(record)
# record.errors[:base] << "This is some custom error message" # record.errors.add :base, "This is some custom error message"
# record.errors[:first_name] << "This is some complex validation" # record.errors.add :first_name, "This is some complex validation"
# # etc... # # etc...
# end # end
# end # end
Expand All @@ -68,7 +68,7 @@ module ActiveModel #:nodoc:
# #
# class TitleValidator < ActiveModel::EachValidator # class TitleValidator < ActiveModel::EachValidator
# def validate_each(record, attribute, value) # def validate_each(record, attribute, value)
# record.errors[attribute] << 'must be Mr. Mrs. or Dr.' unless value.in?(['Mr.', 'Mrs.', 'Dr.']) # record.errors.add attribute, 'must be Mr. Mrs. or Dr.' unless value.in?(['Mr.', 'Mrs.', 'Dr.'])
# end # end
# end # end
# #
Expand Down
4 changes: 2 additions & 2 deletions activerecord/lib/active_record/base.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ module ActiveRecord #:nodoc:
# When joining tables, nested hashes or keys written in the form 'table_name.column_name' # When joining tables, nested hashes or keys written in the form 'table_name.column_name'
# can be used to qualify the table name of a particular condition. For instance: # can be used to qualify the table name of a particular condition. For instance:
# #
# Student.joins(:schools).where(:schools => { :type => 'public' }) # Student.joins(:schools).where(:schools => { :category => 'public' })
# Student.joins(:schools).where('schools.type' => 'public' ) # Student.joins(:schools).where('schools.category' => 'public' )
# #
# == Overwriting default accessors # == Overwriting default accessors
# #
Expand Down
8 changes: 8 additions & 0 deletions activeresource/lib/active_resource/base.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -637,6 +637,10 @@ def prefix(options={}) "#{prefix_call}" end
# Post.element_path(1) # Post.element_path(1)
# # => /posts/1.json # # => /posts/1.json
# #
# class Comment < ActiveResource::Base
# self.site = "http://37s.sunrise.i/posts/:post_id/"
# end
#
# Comment.element_path(1, :post_id => 5) # Comment.element_path(1, :post_id => 5)
# # => /posts/5/comments/1.json # # => /posts/5/comments/1.json
# #
Expand All @@ -663,6 +667,10 @@ def element_path(id, prefix_options = {}, query_options = nil)
# Post.new_element_path # Post.new_element_path
# # => /posts/new.json # # => /posts/new.json
# #
# class Comment < ActiveResource::Base
# self.site = "http://37s.sunrise.i/posts/:post_id/"
# end
#
# Comment.collection_path(:post_id => 5) # Comment.collection_path(:post_id => 5)
# # => /posts/5/comments/new.json # # => /posts/5/comments/new.json
def new_element_path(prefix_options = {}) def new_element_path(prefix_options = {})
Expand Down
2 changes: 1 addition & 1 deletion railties/guides/source/action_controller_overview.textile
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -796,7 +796,7 @@ NOTE: Certain exceptions are only rescuable from the +ApplicationController+ cla


h3. Force HTTPS protocol h3. Force HTTPS protocol


Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reason. Since Rails 3.1 you can now use +force_ssl+ method in your controller to enforce that: Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. Since Rails 3.1 you can now use +force_ssl+ method in your controller to enforce that:


<ruby> <ruby>
class DinnerController class DinnerController
Expand Down
62 changes: 35 additions & 27 deletions railties/guides/source/active_record_querying.textile
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ Active Record provides five different ways of retrieving a single object.


h5. Using a Primary Key h5. Using a Primary Key


Using <tt>Model.find(primary_key)</tt>, you can retrieve the object corresponding to the supplied _primary key_ and matching the supplied options (if any). For example: Using <tt>Model.find(primary_key)</tt>, you can retrieve the object corresponding to the specified _primary key_ that matches any supplied options. For example:


<ruby> <ruby>
# Find the client with primary key (id) 10. # Find the client with primary key (id) 10.
Expand Down Expand Up @@ -170,7 +170,7 @@ h4. Retrieving Multiple Objects


h5. Using Multiple Primary Keys h5. Using Multiple Primary Keys


<tt>Model.find(array_of_primary_key)</tt> also accepts an array of _primary keys_. An array of all the matching records for the supplied _primary keys_ is returned. For example: <tt>Model.find(array_of_primary_key)</tt> accepts an array of _primary keys_, returning an array containing all of the matching records for the supplied _primary keys_. For example:


<ruby> <ruby>
# Find the clients with primary keys 1 and 10. # Find the clients with primary keys 1 and 10.
Expand All @@ -188,74 +188,82 @@ WARNING: <tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::


h4. Retrieving Multiple Objects in Batches h4. Retrieving Multiple Objects in Batches


Sometimes you need to iterate over a large set of records. For example to send a newsletter to all users, to export some data, etc. We often need to iterate over a large set of records, as when we send a newsletter to a large set of users, or when we export data.


The following may seem very straightforward, at first: This may appear straightforward:


<ruby> <ruby>
# Very inefficient when users table has thousands of rows. # This is very inefficient when the users table has thousands of rows.
User.all.each do |user| User.all.each do |user|
NewsLetter.weekly_deliver(user) NewsLetter.weekly_deliver(user)
end end
</ruby> </ruby>


But if the total number of rows in the table is very large, the above approach may vary from being underperforming to being plain impossible. But this approach becomes increasingly impractical as the table size increases, since +User.all.each+ instructs Active Record to fetch _the entire table_ in a single pass, build a model object per row, and then keep the entire array of model objects in memory. Indeed, if we have a large number of records, the entire collection may exceed the amount of memory available.


This is because +User.all.each+ makes Active Record fetch _the entire table_, build a model object per row, and keep the entire array of model objects in memory. Sometimes that is just too many objects and requires too much memory. Rails provides two methods that address this problem by dividing records into memory-friendly batches for processing. The first method, +find_each+, retrieves a batch of records and then yields _each_ record to the block individually as a model. The second method, +find_in_batches+, retrieves a batch of records and then yields _the entire batch_ to the block as an array of models.

TIP: The +find_each+ and +find_in_batches+ methods are intended for use in the batch processing of a large number of records that wouldn't fit in memory all at once. If you just need to loop over a thousand records the regular find methods are the preferred option.


h5. +find_each+ h5. +find_each+


To efficiently iterate over a large table, Active Record provides a batch finder method called +find_each+: The +find_each+ method retrieves a batch of records and then yields _each_ record to the block individually as a model. In the following example, +find_each+ will retrieve 1000 records (the current default for both +find_each+ and +find_in_batches+) and then yield each record individually to the block as a model. This process is repeated until all of the records have been processed:


<ruby> <ruby>
User.find_each do |user| User.find_each do |user|
NewsLetter.weekly_deliver(user) NewsLetter.weekly_deliver(user)
end end
</ruby> </ruby>


*Configuring the batch size* h6. Options for +find_each+

The +find_each+ method accepts most of the options allowed by the regular +find+ method, except for +:order+ and +:limit+, which are reserved for internal use by +find_each+.


Behind the scenes, +find_each+ fetches rows in batches of 1000 and yields them one by one. The size of the underlying batches is configurable via the +:batch_size+ option. Two additional options, +:batch_size+ and +:start+, are available as well.


To fetch +User+ records in batches of 5000, we can use: *+:batch_size+*

The +:batch_size+ option allows you to specify the number of records to be retrieved in each batch, before being passed individually to the block. For example, to retrieve records in batches of 5000:


<ruby> <ruby>
User.find_each(:batch_size => 5000) do |user| User.find_each(:batch_size => 5000) do |user|
NewsLetter.weekly_deliver(user) NewsLetter.weekly_deliver(user)
end end
</ruby> </ruby>


*Starting batch find from a specific primary key* *+:start+*


Records are fetched in ascending order of the primary key, which must be an integer. The +:start+ option allows you to configure the first ID of the sequence whenever the lowest ID is not the one you need. This may be useful, for example, to be able to resume an interrupted batch process, provided it saves the last processed ID as a checkpoint. By default, records are fetched in ascending order of the primary key, which must be an integer. The +:start+ option allows you to configure the first ID of the sequence whenever the lowest ID is not the one you need. This would be useful, for example, if you wanted to resume an interrupted batch process, provided you saved the last processed ID as a checkpoint.


To send newsletters only to users with the primary key starting from 2000, we can use: For example, to send newsletters only to users with the primary key starting from 2000, and to retrieve them in batches of 5000:


<ruby> <ruby>
User.find_each(:batch_size => 5000, :start => 2000) do |user| User.find_each(:start => 2000, :batch_size => 5000) do |user|
NewsLetter.weekly_deliver(user) NewsLetter.weekly_deliver(user)
end end
</ruby> </ruby>


*Additional options* Another example would be if you wanted multiple workers handling the same processing queue. You could have each worker handle 10000 records by setting the appropriate <tt>:start</tt> option on each worker.


+find_each+ accepts the same options as the regular +find+ method. However, +:order+ and +:limit+ are needed internally and hence not allowed to be passed explicitly. NOTE: The +:include+ option allows you to name associations that should be loaded alongside with the models.


h5. +find_in_batches+ h5. +find_in_batches+


You can also work by chunks instead of row by row using +find_in_batches+. This method is analogous to +find_each+, but it yields arrays of models instead: The +find_in_batches+ method is similar to +find_each+, since both retrieve batches of records. The difference is that +find_in_batches+ yields _batches_ to the block as an array of models, instead of individually. The following example will yield to the supplied block an array of up to 1000 invoices at a time, with the final block containing any remaining invoices:


<ruby> <ruby>
# Works in chunks of 1000 invoices at a time. # Give add_invoices an array of 1000 invoices at a time
Invoice.find_in_batches(:include => :invoice_lines) do |invoices| Invoice.find_in_batches(:include => :invoice_lines) do |invoices|
export.add_invoices(invoices) export.add_invoices(invoices)
end end
</ruby> </ruby>


The above will each time yield to the supplied block an array of 1000 invoices (or the remaining invoices, if less than 1000).

NOTE: The +:include+ option allows you to name associations that should be loaded alongside with the models. NOTE: The +:include+ option allows you to name associations that should be loaded alongside with the models.


h6. Options for +find_in_batches+

The +find_in_batches+ method accepts the same +:batch_size+ and +:start+ options as +find_each+, as well as most of the options allowed by the regular +find+ method, except for +:order+ and +:limit+, which are reserved for internal use by +find_in_batches+.

h3. Conditions h3. Conditions


The +where+ method allows you to specify conditions to limit the records returned, representing the +WHERE+-part of the SQL statement. Conditions can either be specified as a string, array, or hash. The +where+ method allows you to specify conditions to limit the records returned, representing the +WHERE+-part of the SQL statement. Conditions can either be specified as a string, array, or hash.
Expand All @@ -268,35 +276,35 @@ WARNING: Building your own conditions as pure strings can leave you vulnerable t


h4. Array Conditions h4. Array Conditions


Now what if that number could vary, say as an argument from somewhere? The find then becomes something like: Now what if that number could vary, say as an argument from somewhere? The find would then take the form:


<ruby> <ruby>
Client.where("orders_count = ?", params[:orders]) Client.where("orders_count = ?", params[:orders])
</ruby> </ruby>


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. 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.


Or if you want to specify two conditions, you can do it like: If you want to specify multiple conditions:


<ruby> <ruby>
Client.where("orders_count = ? AND locked = ?", params[:orders], false) Client.where("orders_count = ? AND locked = ?", params[:orders], false)
</ruby> </ruby>


In this example, the first question mark will be replaced with the value in +params[:orders]+ and the second will be replaced with the SQL representation of +false+, which depends on the adapter. In this example, the first question mark will be replaced with the value in +params[:orders]+ and the second will be replaced with the SQL representation of +false+, which depends on the adapter.


The reason for doing code like: This code is highly preferable:


<ruby> <ruby>
Client.where("orders_count = ?", params[:orders]) Client.where("orders_count = ?", params[:orders])
</ruby> </ruby>


instead of: to this code:


<ruby> <ruby>
Client.where("orders_count = #{params[:orders]}") Client.where("orders_count = #{params[:orders]}")
</ruby> </ruby>


is because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database *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 arguments directly inside the conditions string. because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database *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 arguments directly inside the conditions string.


TIP: For more information on the dangers of SQL injection, see the "Ruby on Rails Security Guide":security.html#sql-injection. TIP: For more information on the dangers of SQL injection, see the "Ruby on Rails Security Guide":security.html#sql-injection.


Expand Down Expand Up @@ -1016,7 +1024,7 @@ You can also use +find_last_by_*+ methods which will find the last record matchi


You can specify an exclamation point (<tt>!</tt>) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+ You can specify an exclamation point (<tt>!</tt>) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+


If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields. For example, +Client.find_by_first_name_and_locked("Ryan", true)+. If you want to find both by name and locked, you can chain these finders together by simply typing "+and+" between the fields. For example, +Client.find_by_first_name_and_locked("Ryan", true)+.


WARNING: Up to and including Rails 3.1, when the number of arguments passed to a dynamic finder method is lesser than the number of fields, say <tt>Client.find_by_name_and_locked("Ryan")</tt>, the behavior is to pass +nil+ as the missing argument. This is *unintentional* and this behavior will be changed in Rails 3.2 to throw an +ArgumentError+. WARNING: Up to and including Rails 3.1, when the number of arguments passed to a dynamic finder method is lesser than the number of fields, say <tt>Client.find_by_name_and_locked("Ryan")</tt>, the behavior is to pass +nil+ as the missing argument. This is *unintentional* and this behavior will be changed in Rails 3.2 to throw an +ArgumentError+.


Expand Down
4 changes: 2 additions & 2 deletions railties/guides/source/active_support_core_extensions.textile
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -1760,7 +1760,7 @@ h4(#string-conversions). Conversions


h5. +ord+ h5. +ord+


Ruby 1.9 defines +ord+ to be the codepoint of the first character of the receiver. Active Support backports +ord+ for single-byte encondings like ASCII or ISO-8859-1 in Ruby 1.8: Ruby 1.9 defines +ord+ to be the codepoint of the first character of the receiver. Active Support backports +ord+ for single-byte encodings like ASCII or ISO-8859-1 in Ruby 1.8:


<ruby> <ruby>
"a".ord # => 97 "a".ord # => 97
Expand All @@ -1774,7 +1774,7 @@ In Ruby 1.8 +ord+ doesn't work in general in UTF8 strings, use the multibyte sup
"à".mb_chars.ord # => 224, in UTF8 "à".mb_chars.ord # => 224, in UTF8
</ruby> </ruby>


Note that the 224 is different in both examples. In ISO-8859-1 "à" is represented as a single byte, 224. Its single-character representattion in UTF8 has two bytes, namely 195 and 160, but its Unicode codepoint is 224. If we call +ord+ on the UTF8 string "à" the return value will be 195 in Ruby 1.8. That is not an error, because UTF8 is unsupported, the call itself would be bogus. Note that the 224 is different in both examples. In ISO-8859-1 "à" is represented as a single byte, 224. Its single-character representation in UTF8 has two bytes, namely 195 and 160, but its Unicode codepoint is 224. If we call +ord+ on the UTF8 string "à" the return value will be 195 in Ruby 1.8. That is not an error, because UTF8 is unsupported, the call itself would be bogus.


INFO: +ord+ is equivalent to +getbyte(0)+. INFO: +ord+ is equivalent to +getbyte(0)+.


Expand Down
6 changes: 2 additions & 4 deletions railties/guides/source/association_basics.textile
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -1229,17 +1229,15 @@ end


If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+. If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.


If you need to evaluate conditions dynamically at runtime, you could use string interpolation in single quotes: If you need to evaluate conditions dynamically at runtime, use a proc:


<ruby> <ruby>
class Customer < ActiveRecord::Base class Customer < ActiveRecord::Base
has_many :latest_orders, :class_name => "Order", has_many :latest_orders, :class_name => "Order",
:conditions => 'orders.created_at > #{10.hours.ago.to_s(:db).inspect}' :conditions => proc { "orders.created_at > #{10.hours.ago.to_s(:db).inspect}" }
end end
</ruby> </ruby>


Be sure to use single quotes.

h6(#has_many-counter_sql). +:counter_sql+ h6(#has_many-counter_sql). +:counter_sql+


Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself. Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
Expand Down
Loading

0 comments on commit e759c88

Please sign in to comment.