diff options
author | Ryan Bigg <radarlistener@gmail.com> | 2008-11-19 22:18:24 +1030 |
---|---|---|
committer | Ryan Bigg <radarlistener@gmail.com> | 2008-11-19 22:18:24 +1030 |
commit | 70a983a6a75d203ae5fdfbdec9c68d33fd79a766 (patch) | |
tree | ab49987a10732e669c2ed30d233e47ae19d9d8f5 /railties/doc/guides/source | |
parent | 9dbb52d97e4ecc97fe793e3ac04a4fd285aa003b (diff) | |
parent | c6e5ffbc5c5df14111d8925c82f143da73f6271b (diff) | |
download | rails-70a983a6a75d203ae5fdfbdec9c68d33fd79a766.tar.gz rails-70a983a6a75d203ae5fdfbdec9c68d33fd79a766.tar.bz2 rails-70a983a6a75d203ae5fdfbdec9c68d33fd79a766.zip |
Merge branch 'master' of git@github.com:lifo/docrails
Diffstat (limited to 'railties/doc/guides/source')
4 files changed, 127 insertions, 141 deletions
diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt index 87f3392551..a369a66bd3 100644 --- a/railties/doc/guides/source/activerecord_validations_callbacks.txt +++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt @@ -49,6 +49,8 @@ We can see how it works by looking at the following script/console output: Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+, +update_attribute+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one. +CAUTION: There are four methods that when called will trigger validation: +save+, +save!+, +update_attributes+ and +update_attributes!+. There is one method left, which is +update_attribute+. This method will update the value of an attribute without triggering any validation, so be careful when using +update_attribute+, since it can let you save your objects in an invalid state. + === The meaning of 'valid' For verifying if an object is valid, Active Record uses the +valid?+ method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the +errors+ instance method. The proccess is really simple: If the +errors+ method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the +errors+ collection. @@ -382,7 +384,7 @@ class Invoice < ActiveRecord::Base end ------------------------------------------------------------------ -If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of +validate+, +validate_on_create+ or +validate_on_update+ methods, passing it the symbols for the methods' names. +If your validation rules are too complicated and you want to break them in small methods, you can implement all of them and call one of +validate+, +validate_on_create+ or +validate_on_update+ methods, passing it the symbols for the methods' names. [source, ruby] ------------------------------------------------------------------ @@ -475,6 +477,80 @@ person.errors.clear person.errors # => nil ------------------------------------------------------------------ +== Callbacks + +Callbacks are methods that get called at certain moments of an object's lifecycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted or loaded from the database. + +=== Callbacks registration + +In order to use the available callbacks, you need to registrate them. There are two ways of doing that. + +=== Registering callbacks by overriding the callback methods + +You can specify the callback method direcly, by overriding it. Let's see how it works using the +before_validation+ callback, which will surprisingly run right before any validation is done. + +[source, ruby] +------------------------------------------------------------------ +class User < ActiveRecord::Base + validates_presence_of :login, :email + + protected + def before_validation + if self.login.nil? + self.login = email unless email.blank? + end + end +end +------------------------------------------------------------------ + +=== Registering callbacks by using macro-style class methods + +The other way you can register a callback method is by implementing it as an ordinary method, and then using a macro-style class method to register it as a callback. The last example could be written like that: + +[source, ruby] +------------------------------------------------------------------ +class User < ActiveRecord::Base + validates_presence_of :login, :email + + before_validation :ensure_login_has_a_value + + protected + def ensure_login_has_a_value + if self.login.nil? + self.login = email unless email.blank? + end + end +end +------------------------------------------------------------------ + +The macro-style class methods can also receive a block. Rails best practices say that you should only use this style of registration if the code inside your block is so short that it fits in just one line. + +[source, ruby] +------------------------------------------------------------------ +class User < ActiveRecord::Base + validates_presence_of :login, :email + + before_create {|user| user.name = user.login.capitalize if user.name.blank?} +end +------------------------------------------------------------------ + +In Rails, the preferred way of registering callbacks is by using macro-style class methods. The main advantages of using macro-style class methods are: + +* You can add more than one method for each type of callback. Those methods will be queued for execution at the same order they were registered. +* Readability, since your callback declarations will live at the beggining of your models' files. + +CAUTION: Remember to always declare the callback methods as being protected or private. These methods should never be public, otherwise it will be possible to call them from code outside the model, violating object encapsulation and exposing implementation details. + +== Callbacks that get triggered when an objects is saved + +* +before_validation+ will be triggered before any validation upon your object is done. You can use this callback to change the object's state so it becames valid. + + + + + + + == Changelog diff --git a/railties/doc/guides/source/association_basics.txt b/railties/doc/guides/source/association_basics.txt index e0c9ee35d3..39d92be2d2 100644 --- a/railties/doc/guides/source/association_basics.txt +++ b/railties/doc/guides/source/association_basics.txt @@ -354,8 +354,8 @@ In designing a data model, you will sometimes find a model that should have a re [source, ruby] ------------------------------------------------------- class Employee < ActiveRecord::Base - has_many :subordinates, :class_name => "User", :foreign_key => "manager_id" - belongs_to :manager, :class_name => "User" + has_many :subordinates, :class_name => "Employee", :foreign_key => "manager_id" + belongs_to :manager, :class_name => "Employee" end ------------------------------------------------------- @@ -1336,7 +1336,7 @@ end ===== +:offset+ -The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records. +The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records. ===== +:order+ @@ -1704,7 +1704,7 @@ end ===== +:offset+ -The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records. +The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records. ===== +:order+ diff --git a/railties/doc/guides/source/configuring.txt b/railties/doc/guides/source/configuring.txt index 1fb73abbb8..945e48cd45 100644 --- a/railties/doc/guides/source/configuring.txt +++ b/railties/doc/guides/source/configuring.txt @@ -113,172 +113,82 @@ There are only a few configuration options for Action View, starting with four o The ERB template handler supplies one additional option: -+ActionView::TemplateHandlers::ERB.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. ++ActionView::TemplateHandlers::ERB.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. See the link:http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/[ERB documentation] for more information. === Configuring Action Mailer There are a number of settings available on +ActionMailer::Base+: ++template_root+ gives the root folder for Action Mailer templates. ++logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Mailer. Set to nil to disable logging. -=== Configuring Active Resource - -=== Configuring Active Support - -== Using Initializers - organization, controlling load order - -== Using an After-Initializer ++smtp_settings+ allows detailed configuration for the +:smtp+ delivery method. It accepts a hash of options, which can include any of these options: -== Rails Environment Settings - -ENV - -== Changelog == - -http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket] +* <tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting. +* <tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it. +* <tt>:domain</tt> - If you need to specify a HELO domain, you can do it here. +* <tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting. +* <tt>:password</tt> - If your mail server requires authentication, set the password in this setting. +* <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>. -* November 5, 2008: Rough outline by link:../authors.html#mgunderloy[Mike Gunderloy] ++sendmail_settings+ allows detailed configuration for the +sendmail+ delivery method. It accepts a hash of options, which can include any of these options: +* <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>. +* <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt>. -actionmailer/lib/action_mailer/base.rb -257: cattr_accessor :logger -267: cattr_accessor :smtp_settings -273: cattr_accessor :sendmail_settings -276: cattr_accessor :raise_delivery_errors -282: cattr_accessor :perform_deliveries -285: cattr_accessor :deliveries -288: cattr_accessor :default_charset -291: cattr_accessor :default_content_type -294: cattr_accessor :default_mime_version -297: cattr_accessor :default_implicit_parts_order -299: cattr_reader :protected_instance_variables - -actionmailer/Rakefile -36: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' - -actionpack/lib/action_controller/base.rb -263: cattr_reader :protected_instance_variables -273: cattr_accessor :asset_host -279: cattr_accessor :consider_all_requests_local -285: cattr_accessor :allow_concurrency -317: cattr_accessor :param_parsers -321: cattr_accessor :default_charset -325: cattr_accessor :logger -329: cattr_accessor :resource_action_separator -333: cattr_accessor :resources_path_names -337: cattr_accessor :request_forgery_protection_token -341: cattr_accessor :optimise_named_routes -351: cattr_accessor :use_accept_header -361: cattr_accessor :relative_url_root ++raise_delivery_errors+ specifies whether to raise an error if email delivery cannot be completed. It defaults to +true+. -actionpack/lib/action_controller/caching/pages.rb -55: cattr_accessor :page_cache_directory -58: cattr_accessor :page_cache_extension ++delivery_method+ defines the delivery method. The allowed values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, and <tt>:test</tt>. -actionpack/lib/action_controller/caching.rb -37: cattr_reader :cache_store -48: cattr_accessor :perform_caching ++perform_deliveries+ specifies whether mail will actually be delivered. By default this is +true+; it can be convenient to set it to +false+ for testing. -actionpack/lib/action_controller/dispatcher.rb -98: cattr_accessor :error_file_path ++default_charset+ tells Action Mailer which character set to use for the body and for encoding the subject. It defaults to +utf-8+. -actionpack/lib/action_controller/mime_type.rb -24: cattr_reader :html_types, :unverifiable_types ++default_content_type+ specifies the default content type used for the main part of the message. It defaults to "text/plain" -actionpack/lib/action_controller/rescue.rb -36: base.cattr_accessor :rescue_responses -40: base.cattr_accessor :rescue_templates ++default_mime_version+ is the default MIME version for the message. It defaults to +1.0+. -actionpack/lib/action_controller/session/active_record_store.rb -60: cattr_accessor :data_column_name -170: cattr_accessor :connection -173: cattr_accessor :table_name -177: cattr_accessor :session_id_column -181: cattr_accessor :data_column -282: cattr_accessor :session_class ++default_implicit_parts_order+ - When a message is built implicitly (i.e. multiple parts are assembled from templates +which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to +<tt>["text/html", "text/enriched", "text/plain"]</tt>. Items that appear first in the array have higher priority in the mail client +and appear last in the mime encoded message. -actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb -44: cattr_accessor :included_tags, :instance_writer => false - -actionpack/lib/action_view/base.rb -189: cattr_accessor :debug_rjs -193: cattr_accessor :warn_cache_misses - -actionpack/lib/action_view/helpers/active_record_helper.rb -7: cattr_accessor :field_error_proc - -actionpack/lib/action_view/helpers/form_helper.rb -805: cattr_accessor :default_form_builder - -actionpack/lib/action_view/template_handlers/erb.rb -47: cattr_accessor :erb_trim_mode - -actionpack/test/active_record_unit.rb -5: cattr_accessor :able_to_connect -6: cattr_accessor :connected +=== Configuring Active Resource -actionpack/test/controller/filters_test.rb -286: cattr_accessor :execution_log +There is a single configuration setting available on +ActiveResource::Base+: -actionpack/test/template/form_options_helper_test.rb -3:TZInfo::Timezone.cattr_reader :loaded_zones ++logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Active Resource. Set to nil to disable logging. -activemodel/lib/active_model/errors.rb -28: cattr_accessor :default_error_messages +=== Configuring Active Support -activemodel/Rakefile -19: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' +There are a few configuration options available in Active Support: -activerecord/lib/active_record/attribute_methods.rb -9: base.cattr_accessor :attribute_types_cached_by_default, :instance_writer => false -11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer => false ++ActiveSupport::BufferedLogger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. ++ActiveSupport::Cache::Store.logger+ specifies the logger to use within cache store operations. -activeresource/lib/active_resource/base.rb -206: cattr_accessor :logger ++ActiveSupport::Logger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. -activeresource/Rakefile -43: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' - -activesupport/lib/active_support/buffered_logger.rb -17: cattr_accessor :silencer - -activesupport/lib/active_support/cache.rb -81: cattr_accessor :logger +=== Configuring Active Model -activesupport/lib/active_support/core_ext/class/attribute_accessors.rb -5:# cattr_accessor :hair_colors -10: def cattr_reader(*syms) -29: def cattr_writer(*syms) -50: def cattr_accessor(*syms) -51: cattr_reader(*syms) -52: cattr_writer(*syms) +Active Model currently has a single configuration setting: -activesupport/lib/active_support/core_ext/logger.rb -34: cattr_accessor :silencer ++ActiveModel::Errors.default_error_messages is an array containing all of the validation error messages. -activesupport/test/core_ext/class/attribute_accessor_test.rb -6: cattr_accessor :foo -7: cattr_accessor :bar, :instance_writer => false +== Using Initializers + organization, controlling load order -activesupport/test/core_ext/module/synchronization_test.rb -6: @target.cattr_accessor :mutex, :instance_writer => false +== Using an After-Initializer -railties/doc/guides/html/creating_plugins.html -786: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field -860: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field +== Rails Environment Settings -railties/lib/rails_generator/base.rb -93: cattr_accessor :logger +ENV -railties/Rakefile -265: rdoc.options << '--line-numbers' << '--inline-source' << '--accessor' << 'cattr_accessor=object' +== Changelog == -railties/test/rails_info_controller_test.rb -12: cattr_accessor :local_request +http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket] -Rakefile -32: rdoc.options << '-A cattr_accessor=object' +* November 5, 2008: Rough outline by link:../authors.html#mgunderloy[Mike Gunderloy] need to look for def self. ??? diff --git a/railties/doc/guides/source/getting_started_with_rails.txt b/railties/doc/guides/source/getting_started_with_rails.txt index 00c6d52eef..9adcc729a3 100644 --- a/railties/doc/guides/source/getting_started_with_rails.txt +++ b/railties/doc/guides/source/getting_started_with_rails.txt @@ -1021,7 +1021,7 @@ class CommentsController < ApplicationController def show @post = Post.find(params[:post_id]) - @comment = Comment.find(params[:id]) + @comment = @post.comments.find(params[:id]) end def new @@ -1033,7 +1033,7 @@ class CommentsController < ApplicationController @post = Post.find(params[:post_id]) @comment = @post.comments.build(params[:comment]) if @comment.save - redirect_to post_comment_path(@post, @comment) + redirect_to post_comment_url(@post, @comment) else render :action => "new" end @@ -1041,14 +1041,14 @@ class CommentsController < ApplicationController def edit @post = Post.find(params[:post_id]) - @comment = Comment.find(params[:id]) + @comment = @post.comments.find(params[:id]) end def update @post = Post.find(params[:post_id]) @comment = Comment.find(params[:id]) if @comment.update_attributes(params[:comment]) - redirect_to post_comment_path(@post, @comment) + redirect_to post_comment_url(@post, @comment) else render :action => "edit" end |