diff options
author | Jeremy Kemper <jeremy@bitsweat.net> | 2009-01-10 12:14:44 -0800 |
---|---|---|
committer | Jeremy Kemper <jeremy@bitsweat.net> | 2009-01-10 12:14:44 -0800 |
commit | 223a1d9451c88800e9fcc93a726fdebec99e2650 (patch) | |
tree | 207b0b671778ac7a0e00829f6f642256b261cb28 /railties/doc/guides/source | |
parent | 13c6c3cfc59ff0b400b294dce15f32752b0fb5f5 (diff) | |
parent | 9fe69b225cfbf12c02ee1433adf3a5aa17bcdf59 (diff) | |
download | rails-223a1d9451c88800e9fcc93a726fdebec99e2650.tar.gz rails-223a1d9451c88800e9fcc93a726fdebec99e2650.tar.bz2 rails-223a1d9451c88800e9fcc93a726fdebec99e2650.zip |
Merge branch 'master' into savepoints
Diffstat (limited to 'railties/doc/guides/source')
-rw-r--r-- | railties/doc/guides/source/activerecord_validations_callbacks.txt | 75 | ||||
-rw-r--r-- | railties/doc/guides/source/command_line.txt | 145 | ||||
-rw-r--r-- | railties/doc/guides/source/finders.txt | 186 | ||||
-rw-r--r-- | railties/doc/guides/source/form_helpers.txt | 121 | ||||
-rw-r--r-- | railties/doc/guides/source/getting_started_with_rails.txt | 2 | ||||
-rw-r--r-- | railties/doc/guides/source/i18n.txt | 260 | ||||
-rw-r--r-- | railties/doc/guides/source/images/i18n/demo_localized_pirate.png | bin | 0 -> 36500 bytes | |||
-rw-r--r-- | railties/doc/guides/source/images/i18n/demo_translated_en.png | bin | 0 -> 32877 bytes | |||
-rw-r--r-- | railties/doc/guides/source/images/i18n/demo_translated_pirate.png | bin | 0 -> 34506 bytes | |||
-rw-r--r-- | railties/doc/guides/source/images/i18n/demo_translation_missing.png | bin | 0 -> 34373 bytes | |||
-rw-r--r-- | railties/doc/guides/source/images/i18n/demo_untranslated.png | bin | 0 -> 32793 bytes | |||
-rw-r--r-- | railties/doc/guides/source/testing_rails_applications.txt | 20 |
12 files changed, 605 insertions, 204 deletions
diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt index 0c82f24e66..e0bb534d0b 100644 --- a/railties/doc/guides/source/activerecord_validations_callbacks.txt +++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt @@ -47,7 +47,7 @@ We can see how it works by looking at the following script/console output: => false ------------------------------------------------------------------ -Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+ 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. +Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+ or +update_attributes+) will result in a SQL update operation. Active Record will use these 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. @@ -155,7 +155,8 @@ This helper validates that the attributes' values are not included in a given se [source, ruby] ------------------------------------------------------------------ class MovieFile < ActiveRecord::Base - validates_exclusion_of :format, :in => %w(mov avi), :message => "Extension %s is not allowed" + validates_exclusion_of :format, :in => %w(mov avi), + :message => "Extension %s is not allowed" end ------------------------------------------------------------------ @@ -170,7 +171,8 @@ This helper validates the attributes's values by testing if they match a given p [source, ruby] ------------------------------------------------------------------ class Product < ActiveRecord::Base - validates_format_of :description, :with => /^[a-zA-Z]+$/, :message => "Only letters allowed" + validates_format_of :description, :with => /^[a-zA-Z]+$/, + :message => "Only letters allowed" end ------------------------------------------------------------------ @@ -183,7 +185,8 @@ This helper validates that the attributes' values are included in a given set. I [source, ruby] ------------------------------------------------------------------ class Coffee < ActiveRecord::Base - validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size" + validates_inclusion_of :size, :in => %w(small medium large), + :message => "%s is not a valid size" end ------------------------------------------------------------------ @@ -223,7 +226,7 @@ end This helper has an alias called +validates_size_of+, it's the same helper with a different name. You can use it if you'd like to. -=== The +validates_numericallity_of+ helper +=== The +validates_numericality_of+ helper This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the +:integer_only+ option set to true, you can specify that only integral numbers are allowed. @@ -232,12 +235,12 @@ If you use +:integer_only+ set to +true+, then it will use the +$$/\A[+\-]?\d+\Z [source, ruby] ------------------------------------------------------------------ class Player < ActiveRecord::Base - validates_numericallity_of :points - validates_numericallity_of :games_played, :integer_only => true + validates_numericality_of :points + validates_numericality_of :games_played, :integer_only => true end ------------------------------------------------------------------ -The default error message for +validates_numericallity_of+ is "_is not a number_". +The default error message for +validates_numericality_of+ is "_is not a number_". === The +validates_presence_of+ helper @@ -282,7 +285,8 @@ There is a +:scope+ option that you can use to specify other attributes that mus [source, ruby] ------------------------------------------------------------------ class Holiday < ActiveRecord::Base - validates_uniqueness_of :name, :scope => :year, :message => "Should happen once per year" + validates_uniqueness_of :name, :scope => :year, + :message => "Should happen once per year" end ------------------------------------------------------------------ @@ -324,9 +328,14 @@ As stated before, the +:on+ option lets you specify when the validation should h [source, ruby] ------------------------------------------------------------------ class Person < ActiveRecord::Base - validates_uniqueness_of :email, :on => :create # => it will be possible to update email with a duplicated value - validates_numericallity_of :age, :on => :update # => it will be possible to create the record with a 'non-numerical age' - validates_presence_of :name, :on => :save # => that's the default + # => it will be possible to update email with a duplicated value + validates_uniqueness_of :email, :on => :create + + # => it will be possible to create the record with a 'non-numerical age' + validates_numericality_of :age, :on => :update + + # => the default + validates_presence_of :name, :on => :save end ------------------------------------------------------------------ @@ -367,7 +376,8 @@ Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object [source, ruby] ------------------------------------------------------------------ class Account < ActiveRecord::Base - validates_confirmation_of :password, :unless => Proc.new { |a| a.password.blank? } + validates_confirmation_of :password, + :unless => Proc.new { |a| a.password.blank? } end ------------------------------------------------------------------ @@ -379,7 +389,8 @@ When the built-in validation helpers are not enough for your needs, you can writ ------------------------------------------------------------------ class Invoice < ActiveRecord::Base def validate_on_create - errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today + errors.add(:expiration_date, "can't be in the past") if + !expiration_date.blank? and expiration_date < Date.today end end ------------------------------------------------------------------ @@ -389,14 +400,17 @@ If your validation rules are too complicated and you want to break them in small [source, ruby] ------------------------------------------------------------------ class Invoice < ActiveRecord::Base - validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value + validate :expiration_date_cannot_be_in_the_past, + :discount_cannot_be_more_than_total_value def expiration_date_cannot_be_in_the_past - errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today + errors.add(:expiration_date, "can't be in the past") if + !expiration_date.blank? and expiration_date < Date.today end def discount_cannot_be_greater_than_total_value - errors.add(:discount, "can't be greater than total value") unless discount <= total_value + errors.add(:discount, "can't be greater than total value") unless + discount <= total_value end end ------------------------------------------------------------------ @@ -454,14 +468,16 @@ person.errors.on(:name) # => nil person = Person.new(:name => "JD") person.valid? # => false -person.errors.on(:name) # => "is too short (minimum is 3 characters)" +person.errors.on(:name) +# => "is too short (minimum is 3 characters)" person = Person.new person.valid? # => false -person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"] +person.errors.on(:name) +# => ["can't be blank", "is too short (minimum is 3 characters)"] ------------------------------------------------------------------ -* +clear+ is used when you intentionally wants to clear all the messages in the +errors+ collection. +* +clear+ is used when you intentionally want to clear all the messages in the +errors+ collection. However, calling +errors.clear+ upon an invalid object won't make it valid: the +errors+ collection will now be empty, but the next time you call +valid?+ or any method that tries to save this object to the database, the validations will run. If any of them fails, the +errors+ collection will get filled again. [source, ruby] ------------------------------------------------------------------ @@ -471,10 +487,15 @@ class Person < ActiveRecord::Base end person = Person.new -puts person.valid? # => false -person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"] +person.valid? # => false +person.errors.on(:name) +# => ["can't be blank", "is too short (minimum is 3 characters)"] + person.errors.clear -person.errors # => nil +person.errors.empty? # => true +p.save # => false +p.errors.on(:name) +# => ["can't be blank", "is too short (minimum is 3 characters)"] ------------------------------------------------------------------ == Callbacks @@ -587,7 +608,7 @@ The +after_initialize+ and +after_find+ callbacks are a bit different from the o == Halting Execution -As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean +false+ (not +nil+) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on. +As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the +before_create+, +before_save+, +before_update+ or +before_destroy+ callback methods returns a boolean +false+ (not +nil+) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on. == Callback classes @@ -667,7 +688,7 @@ end === Registering observers -If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register then in our application's *config/environment.rb* file. In this file there is a commented out line where we can define the observers that our application should load at start-up. +If you payed attention, you may be wondering where Active Record Observers are referenced in our applications, so they get instantiate and begin to interact with our models. For observers to work we need to register them somewhere. The usual place to do that is in our application's *config/environment.rb* file. In this file there is a commented out line where we can define the observers that our application should load at start-up. [source, ruby] ------------------------------------------------------------------ @@ -675,6 +696,10 @@ If you payed attention, you may be wondering where Active Record Observers are r config.active_record.observers = :registration_observer, :auditor ------------------------------------------------------------------ +You can uncomment the line with +config.active_record.observers+ and change the symbols for the name of the observers that should be registered. + +It's also possible to register callbacks in any of the files living at *config/environments/*, if you want an observer to work only in a specific environment. There is not a +config.active_record.observers+ line at any of those files, but you can simply add it. + === Where to put the observers' source files By convention, you should always save your observers' source files inside *app/models*. diff --git a/railties/doc/guides/source/command_line.txt b/railties/doc/guides/source/command_line.txt index 1ad2e75c51..8a887bd001 100644 --- a/railties/doc/guides/source/command_line.txt +++ b/railties/doc/guides/source/command_line.txt @@ -52,7 +52,7 @@ NOTE: This output will seem very familiar when we get to the `generate` command. === server === -Let's try it! The `server` command launches a small web server written in Ruby named WEBrick which was also installed when you installed Rails. You'll use this any time you want to view your work through a web browser. +Let's try it! The `server` command launches a small web server named WEBrick which comes bundled with Ruby. You'll use this any time you want to view your work through a web browser. NOTE: WEBrick isn't your only option for serving Rails. We'll get to that in a later section. [XXX: which section] @@ -99,7 +99,7 @@ Using generators will save you a large amount of time by writing *boilerplate co Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator: -NOTE: All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can try the command without any parameters (like `rails` or `./script/generate`). For others, you can try adding `--help` or `-h` to the end, as in `./script/server --help`. +NOTE: All Rails console utilities have help text. As with most *NIX utilities, you can try adding `--help` or `-h` to the end, for example `./script/server --help`. [source,shell] ------------------------------------------------------ @@ -200,24 +200,47 @@ Examples: creates a Post model with a string title, text body, and published flag. ------------------------------------------------------ -Let's set up a simple model called "HighScore" that will keep track of our highest score on video games we play. Then we'll wire up our controller and view to modify and list our scores. +But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A *scaffold* in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above. + +Let's set up a simple resource called "HighScore" that will keep track of our highest score on video games we play. [source,shell] ------------------------------------------------------ -$ ./script/generate model HighScore id:integer game:string score:integer - exists app/models/ - exists test/unit/ - exists test/fixtures/ - create app/models/high_score.rb - create test/unit/high_score_test.rb - create test/fixtures/high_scores.yml - create db/migrate - create db/migrate/20081126032945_create_high_scores.rb +$ ./script/generate scaffold HighScore game:string score:integer + exists app/models/ + exists app/controllers/ + exists app/helpers/ + create app/views/high_scores + create app/views/layouts/ + exists test/functional/ + create test/unit/ + create public/stylesheets/ + create app/views/high_scores/index.html.erb + create app/views/high_scores/show.html.erb + create app/views/high_scores/new.html.erb + create app/views/high_scores/edit.html.erb + create app/views/layouts/high_scores.html.erb + create public/stylesheets/scaffold.css + create app/controllers/high_scores_controller.rb + create test/functional/high_scores_controller_test.rb + create app/helpers/high_scores_helper.rb + route map.resources :high_scores +dependency model + exists app/models/ + exists test/unit/ + create test/fixtures/ + create app/models/high_score.rb + create test/unit/high_score_test.rb + create test/fixtures/high_scores.yml + exists db/migrate + create db/migrate/20081217071914_create_high_scores.rb ------------------------------------------------------ -Taking it from the top, we have the *models* directory, where all of your data models live. *test/unit*, where all the unit tests live (gasp! -- unit tests!), fixtures for those tests, a test, the *migrate* directory, where the database-modifying migrations live, and a migration to create the `high_scores` table with the right fields. +Taking it from the top - the generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the `high_scores` table and fields), takes care of the route for the *resource*, and new tests for everything. + +The migration requires that we *migrate*, that is, run some Ruby code (living in that `20081217071914_create_high_scores.rb`) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the `rake db:migrate` command. We'll talk more about Rake in-depth in a little while. -The migration requires that we *migrate*, that is, run some Ruby code (living in that `20081126032945_create_high_scores.rb`) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the `rake db:migrate` command. We'll talk more about Rake in-depth in a little while. +NOTE: Hey. Install the sqlite3-ruby gem while you're at it. `gem install sqlite3-ruby` [source,shell] ------------------------------------------------------ @@ -231,23 +254,87 @@ $ rake db:migrate NOTE: Let's talk about unit tests. Unit tests are code that tests and makes assertions about code. In unit testing, we take a little part of code, say a method of a model, and test its inputs and outputs. Unit tests are your friend. The sooner you make peace with the fact that your quality of life will drastically increase when you unit test your code, the better. Seriously. We'll make one in a moment. -Yo! Let's shove a small table into our greeting controller and view, listing our sweet scores. +Let's see the interface Rails created for us. ./script/server; http://localhost:3000/high_scores -[source,ruby] +We can create new high scores (55,160 on Space Invaders!) + +=== console === +The `console` command lets you interact with your Rails application from the command line. On the underside, `script/console` uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website. + +=== dbconsole === +`dbconsole` figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3. + +=== plugin === +The `plugin` command simplifies plugin management; think a miniature version of the Gem utility. Let's walk through installing a plugin. You can call the sub-command *discover*, which sifts through repositories looking for plugins, or call *source* to add a specific repository of plugins, or you can specify the plugin location directly. + +Let's say you're creating a website for a client who wants a small accounting system. Every event having to do with money must be logged, and must never be deleted. Wouldn't it be great if we could override the behavior of a model to never actually take its record out of the database, but *instead*, just set a field? + +There is such a thing! The plugin we're installing is called "acts_as_paranoid", and it lets models implement a "deleted_at" column that gets set when you call destroy. Later, when calling find, the plugin will tack on a database check to filter out "deleted" things. + +[source,shell] +------------------------------------------------------ +$ ./script/plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_paranoid ++ ./CHANGELOG ++ ./MIT-LICENSE +... +... ------------------------------------------------------ -class GreetingController < ApplicationController - def hello - if request.post? - score = HighScore.new(params[:high_score]) - if score.save - flash[:notice] = "New score posted!" - end - end - - @scores = HighScore.find(:all) - end -end +=== runner === +`runner` runs Ruby code in the context of Rails non-interactively. For instance: + +[source,shell] ------------------------------------------------------ +$ ./script/runner "Model.long_running_method" +------------------------------------------------------ + +=== destroy === +Think of `destroy` as the opposite of `generate`. It'll figure out what generate did, and undo it. Believe you-me, the creation of this tutorial used this command many times! -XXX: Go with scaffolding instead, modifying greeting controller for high scores seems dumb. +[source,shell] +------------------------------------------------------ +$ ./script/generate model Oops + exists app/models/ + exists test/unit/ + exists test/fixtures/ + create app/models/oops.rb + create test/unit/oops_test.rb + create test/fixtures/oops.yml + exists db/migrate + create db/migrate/20081221040817_create_oops.rb +$ ./script/destroy model Oops + notempty db/migrate + notempty db + rm db/migrate/20081221040817_create_oops.rb + rm test/fixtures/oops.yml + rm test/unit/oops_test.rb + rm app/models/oops.rb + notempty test/fixtures + notempty test + notempty test/unit + notempty test + notempty app/models + notempty app +------------------------------------------------------ + +=== about === +Check it: Version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version! `about` is useful when you need to ask help, check if a security patch might affect you, or when you need some stats for an existing Rails installation. + +[source,shell] +------------------------------------------------------ +$ ./script/about +About your application's environment +Ruby version 1.8.6 (i486-linux) +RubyGems version 1.3.1 +Rails version 2.2.0 +Active Record version 2.2.0 +Action Pack version 2.2.0 +Active Resource version 2.2.0 +Action Mailer version 2.2.0 +Active Support version 2.2.0 +Edge Rails revision unknown +Application root /home/commandsapp +Environment development +Database adapter sqlite3 +Database schema version 20081217073400 +------------------------------------------------------
\ No newline at end of file diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt index 4c70c2b20b..88e7c15cb6 100644 --- a/railties/doc/guides/source/finders.txt +++ b/railties/doc/guides/source/finders.txt @@ -1,7 +1,7 @@ Rails Finders ============= -This guide covers the +find+ method defined in +ActiveRecord::Base+, as well as other ways of finding particular instances of your models. By using this guide, you will be able to: +This guide covers the +find+ method defined in ActiveRecord::Base, as well as other ways of finding particular instances of your models. By using this guide, you will be able to: * Find records using a variety of methods and conditions * Specify the order, retrieved attributes, grouping, and other properties of the found records @@ -50,7 +50,7 @@ Active Record will perform queries on the database for you and is compatible wit == 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. For finding records, the key method is +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: +ActiveRecord::Base has methods defined on it to make interacting with your database and the tables within it much, much easier. For finding records, the key method is +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: [source, sql] ------------------------------------------------------- @@ -74,9 +74,9 @@ SELECT * FROM clients WHERE (clients.id IN (1,2)) created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">] ------------------------------------------------------- -Note that if you pass in a list of numbers that the result will be returned as an array, not as a single +Client+ object. +Note that if you pass in a list of numbers that the result will be returned as an array, not as a single Client object. -NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a +RecordNotFound+ exception. +NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a RecordNotFound exception. If you wanted to find the first Client object you would simply type +Client.first+ and that would find the first client in your clients table: @@ -143,7 +143,7 @@ WARNING: Building your own conditions as pure strings can leave you vulnerable t === 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 +false+ 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. +Now what if that number could vary, say as a argument 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 the SQL representation of +false+, which depends on the adapter. The reason for doing code like: @@ -159,7 +159,7 @@ instead of: Client.first(:conditions => "orders_count = #{params[:orders]}") ------------------------------------------------------- -is because of parameter 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 parameters directly inside the conditions string. +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. TIP: For more information on the dangers of SQL injection, see the link:../security.html#_sql_injection[Ruby on Rails Security Guide]. @@ -185,7 +185,7 @@ SELECT * FROM users WHERE (created_at IN '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: +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: [source, ruby] ------------------------------------------------------- @@ -224,7 +224,7 @@ Client.all(:conditions => ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]]) ------------------------------------------------------- -Just like in Ruby. +Just like in Ruby. If you want a shorter syntax be sure to check out the <<_hash_conditions, Hash Conditions>> section later on in the guide. === Placeholder Conditions === @@ -238,13 +238,83 @@ Client.all(:conditions => This makes for clearer readability if you have a large number of variable conditions. +=== Hash Conditions + +Rails also allows you to pass in a hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want conditionalised and the values of how you want to conditionalise them: + +[source, ruby] +------------------------------------------------------- +Client.all(:conditions => { :locked => true }) +------------------------------------------------------- + +The field name does not have to be a symbol it can also be a string: + +[source, ruby] +------------------------------------------------------- +Client.all(:conditions => { 'locked' => true }) +------------------------------------------------------- + +The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section. + +[source, ruby] +------------------------------------------------------- +Client.all(:conditions => { :created_at => (Time.now.midnight - 1.day)..Time.now.midnight}) +------------------------------------------------------- + +This will find all clients created yesterday by using a BETWEEN sql statement: + +[source, sql] +------------------------------------------------------- +SELECT * FROM `clients` WHERE (`clients`.`created_at` BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00') +------------------------------------------------------- + +This demonstrates a shorter syntax for the examples in <<_array_conditions, Array Conditions>> + +You can also join in tables and specify their columns in the hash: + +[source, ruby] +------------------------------------------------------- +Client.all(:include => "orders", :conditions => { 'orders.created_at' => (Time.now.midnight - 1.day)..Time.now.midnight }) +------------------------------------------------------- + +An alternative and cleaner syntax to this is: + +[source, ruby] +------------------------------------------------------- +Client.all(:include => "orders", :conditions => { :orders => { :created_at => (Time.now.midnight - 1.day)..Time.now.midnight } }) +------------------------------------------------------- + +This will find all clients who have orders that were created yesterday, again using a BETWEEN expression. + +If you want to find records using the IN expression you can pass an array to the conditions hash: + +[source, ruby] +------------------------------------------------------- +Client.all(:include => "orders", :conditions => { :orders_count => [1,3,5] } +------------------------------------------------------- + +This code will generate SQL like this: + +[source, sql] +------------------------------------------------------- +SELECT * FROM `clients` WHERE (`clients`.`orders_count` IN (1,2,3)) +------------------------------------------------------- + == Ordering -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")+ +If you're getting a set of records and want to order them in ascending order by the +created_at+ field in your table, you can use +Client.all(:order => "created_at")+. If you'd like to order it in descending order, just tell it to do that using +Client.all(:order => "created_at desc")+. The value for this option is passed in as sanitized SQL and allows you to sort via multiple fields: +Client.all(:order => "created_at desc, orders_count asc")+. == Selecting Certain Fields -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. +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 1+ on your database. + +Be careful because this also means you're initializing a model object with only the fields that you've selected. If you attempt to access a field that is not in the initialized record you'll receive: + +------------------------------------------------------- +ActiveRecord::MissingAttributeError: missing attribute: <attribute> +------------------------------------------------------- + +Where <attribute> is the atrribute you asked for. The +id+ method will not raise the +ActiveRecord::MissingAttributeError+, so just be careful when working with associations because they need the +id+ method to function properly. You can also call SQL functions within the select option. For example, if you would like to only grab a single record per unique value in a certain field by using the +DISTINCT+ function you can do it like this: +Client.all(:select => "DISTINCT(name)")+. @@ -294,16 +364,29 @@ The SQL that would be executed would be something like this: SELECT * FROM orders GROUP BY date(created_at) ------------------------------------------------------- +== Having + +The +:having+ option allows you to specify SQL and acts as a kind of a filter on the group option. +:having+ can only be specified when +:group+ is specified. + +An example of using it would be: + +[source, ruby] +------------------------------------------------------- +Order.all(:group => "date(created_at)", :having => ["created_at > ?", 1.month.ago]) +------------------------------------------------------- + +This will return single order objects for each day, but only for the last month. + == 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 +Active Record::ReadOnlyRecord+ exception. To set this option, specify it like this: ++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 exception. To set this option, specify it like this: [source, ruby] ------------------------------------------------------- Client.first(:readonly => true) ------------------------------------------------------- -If you assign this record to a variable +client+, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception: +If you assign this record to a variable client, calling the following code will raise an ActiveRecord::ReadOnlyRecord exception: [source, ruby] ------------------------------------------------------- @@ -324,13 +407,23 @@ Topic.transaction do end ------------------------------------------------------- +You can also pass SQL to this option to allow different types of locks. For example, MySQL has an expression called LOCK IN SHARE MODE where you can lock a record but still allow other queries to read it. To specify this expression just pass it in as the lock option: + +[source, ruby] +------------------------------------------------------- +Topic.transaction do + t = Topic.find(params[:id], :lock => "LOCK IN SHARE MODE") + t.increment!(:views) +end +------------------------------------------------------- + == Making It All Work Together -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 Active Record 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+ method Active Record will use the last one you specified. This is because the options passed to find are a hash and defining the same key twice in a hash will result in the last definition being used. == Eager Loading -Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use +Client.all(:include => :address)+. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all, :include => [:address, :mailing_address]). Include 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: +Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use +Client.all(:include => :address)+. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all, :include => [:address, :mailing_address])+. Include 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: [source, sql] ------------------------------------------------------- @@ -341,9 +434,10 @@ 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. +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 and is often called the "N+1 query problem". The problem is that the more queries your server has to execute, the slower it will run. -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: +If you wanted to get all the addresses for a client in the same query you would do +Client.all(:joins => :address)+. +If 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: [source, sql] ------------------------------------------------------- @@ -366,44 +460,44 @@ When using eager loading you can specify conditions for the columns of the table [source, ruby] ------------------------------------------------------- Client.first(:include => "orders", :conditions => - ["orders.created_at >= ? AND orders.created_at <= ?", Time.now - 2.weeks, Time.now]) + ["orders.created_at >= ? AND orders.created_at <= ?", 2.weeks.ago, Time.now]) ------------------------------------------------------- == Dynamic finders -For every field (also known as an attribute) you define in your table, Active Record provides a finder method. 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 Active Record. If you have also have a +locked+ field on the client model, you also get +find_by_locked+ and +find_all_by_locked+. +For every field (also known as an attribute) you define in your table, Active Record provides a finder method. 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 Active Record. If you have also have a +locked+ field on the Client model, you also get +find_by_locked+ and +find_all_by_locked+. -You can do +find_last_by_*+ methods too which will find the last record matching your parameter. +You can do +find_last_by_*+ methods too which will find the last record matching your argument. -You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!('Ryan')+ +You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an ActiveRecord::RecordNotFound error if they do not return any records, like +Client.find_by_name!("Ryan")+ -If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_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_name_and_locked("Ryan", true)+. -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')+: +There's another set of dynamic finders that let you find or create/initialize objects if they aren't found. 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")+: [source,sql] ------------------------------------------------------- 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') + 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 act similar to calling +new+ with the parameters you passed in. For example: ++find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will act similar to calling +new+ with the arguments you passed in. For example: [source, ruby] ------------------------------------------------------- client = Client.find_or_initialize_by_name('Ryan') ------------------------------------------------------- -will either assign an existing client object with the name 'Ryan' to the client local variable, or initialize new object similar to calling +Client.new(:name => 'Ryan')+. From here, you can modify other fields in client by calling the attribute setters on it: +client.locked = true+ and when you want to write it to the database just call +save+ on it. +will either assign an existing client object with the name 'Ryan' to the client local variable, or initialize a new object similar to calling +Client.new(:name => 'Ryan')+. From here, you can modify other fields in client by calling the attribute setters on it: +client.locked = true+ and when you want to write it to the database just call +save+ on it. == Finding By SQL -If you'd like to use your own SQL to find records a table you can use +find_by_sql+. The +find_by_sql+ method 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: +If you'd like to use your own SQL to find records in a table you can use +find_by_sql+. The +find_by_sql+ method will return an array of objects even the underlying query returns just a single record. For example you could run this query: [source, ruby] ------------------------------------------------------- @@ -423,7 +517,7 @@ Client.connection.select_all("SELECT * FROM `clients` WHERE `id` = '1'") == 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 existing 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. +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 existing 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 resources. == Named Scopes @@ -431,7 +525,7 @@ Named scopes are another way to add custom finding behavior to the models in the === Simple Named Scopes -Suppose want to find all clients who are male. You could use this code: +Suppose we want to find all clients who are male. You could use this code: [source, ruby] ------------------------------------------------------- @@ -451,7 +545,7 @@ class Client < ActiveRecord::Base end ------------------------------------------------------- -You can call this new named_scope with +Client.active.all+ and this will do the same query as if we just used +Client.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+. +You can call this new named_scope with +Client.active.all+ and this will do the same query as if we just used +Client.all(:conditions => ["active = ?", true])+. If you want to find the first client within this named scope you could do +Client.active.first+. === Combining Named Scopes @@ -480,7 +574,7 @@ class Client < ActiveRecord::Base end ------------------------------------------------------- -This looks like 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: +This looks like 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: [source, ruby] ------------------------------------------------------- @@ -489,11 +583,11 @@ class Client < ActiveRecord::Base end ------------------------------------------------------- -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. +And now every time the +recent+ named scope is called, the code in the lambda block will be executed, so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded. === Named Scopes with Multiple Models -In a named scope you can use +:include+ and +:joins+ options just like in find. +In a named scope you can use +:include+ and +:joins+ options just like in +find+. [source, ruby] ------------------------------------------------------- @@ -507,7 +601,7 @@ This method, called as +Client.active_within_2_weeks.all+, will return all clien === Arguments to Named Scopes -If you want to pass a named scope a compulsory argument, just specify it as a block parameter like this: +If you want to pass to a named scope a required arugment, just specify it as a block argument like this: [source, ruby] ------------------------------------------------------- @@ -516,7 +610,7 @@ class Client < ActiveRecord::Base 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. +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 prefix the arugment with an *. [source, ruby] ------------------------------------------------------- @@ -553,14 +647,14 @@ Just like named scopes, anonymous scopes can be stacked, either with other anony == Existence of Objects -If you simply want to check for the existence 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. +If you simply want to check for the existence 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+. [source, ruby] ------------------------------------------------------- Client.exists?(1) ------------------------------------------------------- -The above code will check for the existence of a clients table record with the id of 1 and return true if it exists. +The +exists?+ method also takes multiple ids, but the catch is that it will return true if any one of those records exists. [source, ruby] ------------------------------------------------------- @@ -569,8 +663,6 @@ Client.exists?(1,2,3) Client.exists?([1,2,3]) ------------------------------------------------------- -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: [source, ruby] @@ -593,10 +685,10 @@ Which will execute: [source, sql] ------------------------------------------------------- -SELECT count(*) AS count_all FROM clients WHERE (first_name = 1) +SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan') ------------------------------------------------------- -You can also use +include+ or +joins+ for this to do something a little more complex: +You can also use +:include+ or +:joins+ for this to do something a little more complex: [source, ruby] ------------------------------------------------------- @@ -609,7 +701,7 @@ 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') + (clients.first_name = 'Ryan' AND orders.status = 'received') ------------------------------------------------------- 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. @@ -619,7 +711,7 @@ This code specifies +clients.first_name+ just in case one of the join tables has 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. +For options, please see the parent section, <<_calculations, Calculations>>. === Average @@ -632,7 +724,7 @@ Client.average("orders_count") 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, Calculations>> +For options, please see the parent section, <<_calculations, Calculations>>. === Minimum @@ -677,6 +769,14 @@ Thanks to Mike Gunderloy for his tips on creating this guide. http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket] +* December 23 2008: Xavier Noria suggestions added! From http://rails.lighthouseapp.com/projects/16213/tickets/16-activerecord-finders#ticket-16-27[this ticket] and http://rails.lighthouseapp.com/projects/16213/tickets/16-activerecord-finders#ticket-16-28[this ticket] and http://rails.lighthouseapp.com/projects/16213/tickets/16-activerecord-finders#ticket-16-29[this ticket] +* December 22 2008: Added section on having. +* December 22 2008: Added description of how to make hash conditions use an IN expression http://rails.loglibrary.com/chats/15279234[mentioned here] +* December 22 2008: Mentioned using SQL as values for the lock option as mentioned in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-24[this ticket] +* December 21 2008: Fixed http://rails.lighthouseapp.com/projects/16213/tickets/16-activerecord-finders#ticket-16-22[this ticket] minus two points; the lock SQL syntax and the having option. +* December 21 2008: Added more to the has conditions section. +* December 17 2008: Fixed up syntax errors. +* December 16 2008: Covered hash conditions that were introduced in Rails 2.2.2. * December 1 2008: Added using an SQL function example to Selecting Certain Fields section as per http://rails.lighthouseapp.com/projects/16213/tickets/36-adding-an-example-for-using-distinct-to-ar-finders[this ticket] * November 23 2008: Added documentation for +find_by_last+ and +find_by_bang!+ * November 21 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-13[this comment] and http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-14[this comment] diff --git a/railties/doc/guides/source/form_helpers.txt b/railties/doc/guides/source/form_helpers.txt index 88ca74a557..d09ad15a90 100644 --- a/railties/doc/guides/source/form_helpers.txt +++ b/railties/doc/guides/source/form_helpers.txt @@ -247,7 +247,7 @@ A nice thing about `f.text_field` and other helper methods is that they will pre Relying on record identification ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -In the previous chapter we handled the Article model. This model is directly available to users of our application and, following the best practices for developing with Rails, we should declare it *a resource*. +In the previous chapter we handled the Article model. This model is directly available to users of our application, so -- following the best practices for developing with Rails -- we should declare it *a resource*. When dealing with RESTful resources, our calls to `form_for` can get significantly easier if we rely on *record identification*. In short, we can just pass the model instance and have Rails figure out model name and the rest: @@ -291,15 +291,13 @@ Here we have a list of cities where their names are presented to the user, but i The select tag and options ~~~~~~~~~~~~~~~~~~~~~~~~~~ -The most generic helper is `select_tag`, which -- as the name implies -- simply generates the `SELECT` tag that encapsulates the options: +The most generic helper is `select_tag`, which -- as the name implies -- simply generates the `SELECT` tag that encapsulates an options string: ---------------------------------------------------------------------------- <%= select_tag(:city_id, '<option value="1">Lisabon</option>...') %> ---------------------------------------------------------------------------- -This is a start, but it doesn't dynamically create our option tags. We had to pass them in as a string. - -We can generate option tags with the `options_for_select` helper: +This is a start, but it doesn't dynamically create our option tags. We can generate option tags with the `options_for_select` helper: ---------------------------------------------------------------------------- <%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %> @@ -311,9 +309,9 @@ output: ... ---------------------------------------------------------------------------- -For input data we used a nested array where each element has two elements: visible value (name) and internal value (ID). +For input data we used a nested array where each item has two elements: option text (city name) and option value (city id). -Now you can combine `select_tag` and `options_for_select` to achieve the desired, complete markup: +Knowing this, you can combine `select_tag` and `options_for_select` to achieve the desired, complete markup: ---------------------------------------------------------------------------- <%= select_tag(:city_id, options_for_select(...)) %> @@ -333,13 +331,114 @@ output: So whenever Rails sees that the internal value of an option being generated matches this value, it will add the `selected` attribute to that option. -Select boxes for dealing with models -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Select helpers for dealing with models +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Until now we've covered how to make generic select boxes, but in most cases our form controls will be tied to a specific database model. So, to continue from our previous examples, let's assume that we have a "Person" model with a `city_id` attribute. +Consistent with other form helpers, when dealing with models we drop the `"_tag"` suffix from `select_tag` that we used in previous examples: + ---------------------------------------------------------------------------- -... +# controller: +@person = Person.new(:city_id => 2) + +# view: +<%= select(:person, :city_id, [['Lisabon', 1], ['Madrid', 2], ...]) %> +---------------------------------------------------------------------------- + +Notice that the third parameter, the options array, is the same kind of argument we pass to `options_for_select`. One thing that we have as an advantage here is that we don't have to worry about pre-selecting the correct city if the user already has one -- Rails will do this for us by reading from `@person.city_id` attribute. + +As before, if we were to use `select` helper on a form builder scoped to `@person` object, the syntax would be: + +---------------------------------------------------------------------------- +# select on a form builder +<%= f.select(:city_id, ...) %> +---------------------------------------------------------------------------- + +Option tags from a collection of arbitrary objects +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Until now we were generating option tags from nested arrays with the help of `options_for_select` method. Data in our array were raw values: + +---------------------------------------------------------------------------- +<%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %> +---------------------------------------------------------------------------- + +But what if we had a *City* model (perhaps an ActiveRecord one) and we wanted to generate option tags from a collection of those objects? One solution would be to make a nested array by iterating over them: + +---------------------------------------------------------------------------- +<% cities_array = City.find(:all).map { |city| [city.name, city.id] } %> +<%= options_for_select(cities_array) %> +---------------------------------------------------------------------------- + +This is a perfectly valid solution, but Rails provides us with a less verbose alternative: `options_from_collection_for_select`. This helper expects a collection of arbitrary objects and two additional arguments: the names of the methods to read the option *value* and *text* from, respectively: + +---------------------------------------------------------------------------- +<%= options_from_collection_for_select(City.all, :id, :name) %> +---------------------------------------------------------------------------- + +As the name implies, this only generates option tags. A method to go along with it is `collection_select`: + +---------------------------------------------------------------------------- +<%= collection_select(:person, :city_id, City.all, :id, :name) %> ---------------------------------------------------------------------------- -...
\ No newline at end of file +To recap, `options_from_collection_for_select` are to `collection_select` what `options_for_select` are to `select`. + +Time zone and country select +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To leverage time zone support in Rails, we have to ask our users what time zone they are in. Doing so would require generating select options from a list of pre-defined TimeZone objects using `collection_select`, but we can simply use the `time_zone_select` helper that already wraps this: + +---------------------------------------------------------------------------- +<%= time_zone_select(:person, :city_id) %> +---------------------------------------------------------------------------- + +There is also `time_zone_options_for_select` helper for a more manual (therefore more customizable) way of doing this. Read the API documentation to learn about the possible arguments for these two methods. + +When it comes to country select, Rails _used_ to have the built-in helper `country_select` but was extracted to a plugin. +TODO: plugin URL + + +Miscellaneous +------------- + +File upload form +~~~~~~~~~~~~~~~~ + +:multipart - If set to true, the enctype is set to "multipart/form-data". + +Scoping out form controls with `fields_for` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Creates a scope around a specific model object like `form_for`, but doesn’t create the form tags themselves. This makes `fields_for` suitable for specifying additional model objects in the same form: + +Making custom form builders +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can also build forms using a customized FormBuilder class. Subclass FormBuilder and override or define some more helpers, then use your custom builder. For example, let’s say you made a helper to automatically add labels to form inputs. + +---------------------------------------------------------------------------- +<% form_for :person, @person, :url => { :action => "update" }, :builder => LabellingFormBuilder do |f| %> + <%= f.text_field :first_name %> + <%= f.text_field :last_name %> + <%= text_area :person, :biography %> + <%= check_box_tag "person[admin]", @person.company.admin? %> +<% end %> +---------------------------------------------------------------------------- + + +* `form_for` within a namespace + +---------------------------------------------------------------------------- +select_tag(name, option_tags = nil, html_options = { :multiple, :disabled }) + +select(object, method, choices, options = {}, html_options = {}) +options_for_select(container, selected = nil) + +collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {}) +options_from_collection_for_select(collection, value_method, text_method, selected = nil) + +time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone) +time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {}) +---------------------------------------------------------------------------- diff --git a/railties/doc/guides/source/getting_started_with_rails.txt b/railties/doc/guides/source/getting_started_with_rails.txt index b66d2f6f9e..58eff9fd3d 100644 --- a/railties/doc/guides/source/getting_started_with_rails.txt +++ b/railties/doc/guides/source/getting_started_with_rails.txt @@ -984,7 +984,7 @@ end This creates +comments+ as a _nested resource_ within +posts+. This is another part of capturing the hierarchical relationship that exists between posts and comments. -TIP: For more information on routing, see the link:../routing_outside_in[Rails Routing from the Outside In] guide. +TIP: For more information on routing, see the link:../routing_outside_in.html[Rails Routing from the Outside In] guide. === Generating a Controller diff --git a/railties/doc/guides/source/i18n.txt b/railties/doc/guides/source/i18n.txt index 76f081e0bc..ba3cc42a5b 100644 --- a/railties/doc/guides/source/i18n.txt +++ b/railties/doc/guides/source/i18n.txt @@ -12,7 +12,7 @@ Internationalization is a complex problem. Natural languages differ in so many w === The overall architecture of the library -To solve this the Ruby I18n gem is split into two parts: +Thus, the Ruby I18n gem is split into two parts: * The public API which is just a Ruby module with a bunch of public methods and definitions how the library works. * A shipped backend (which is intentionally named the Simple backend) that implements these methods. @@ -29,6 +29,14 @@ translate # lookup translations localize # localize Date and Time objects to local formats ------------------------------------------------------- +These have the aliases #t and #l so you can use them like this: + +[source, ruby] +------------------------------------------------------- +I18n.t 'store.title' +I18n.l Time.now +------------------------------------------------------- + There are also attribute readers and writers for the following attributes: [source, ruby] @@ -46,9 +54,30 @@ There are just a few, simple steps to get up and running with a I18n support for === Configure the I18n module -First of all you want to tell the I18n library where it can find your custom translation files. You might also want to set your default locale to something else than English. +Rails will wire up all required settings for you with sane defaults. If you need different settings you can overwrite them easily. + +The I18n library will use English (:en) as a *default locale* by default. I.e if you don't set a different locale, :en will be used for looking up translations. Also, Rails adds all files from config/locales/*.rb,yml to your translations load path. + +The *translations load path* (I18n.load_path) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you. + +(Hint: The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.) -You can pick whatever directory and translation file naming scheme makes sense for you. The simplest thing possible is probably to put the following into an initializer: +The default environment.rb says: + +[source, ruby] +------------------------------------------------------- +# The internationalization framework can be changed +# to have another default locale (standard is :en) or more load paths. +# All files from config/locales/*.rb,yml are added automatically. +# config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] +# config.i18n.default_locale = :de +------------------------------------------------------- + +=== Optional: custom I18n configuration setup + +For the sake of completeness let's mention that if you do not want to use the environment for some reason you can always wire up things manually, too. + +To tell the I18n library where it can find your custom translation files you can specify the load path anywhere in your application - just make sure it gets run before any translations are actually looked up. You might also want to change the default locale. The simplest thing possible is to put the following into an initializer: [source, ruby] ------------------------------------------------------- @@ -58,14 +87,12 @@ You can pick whatever directory and translation file naming scheme makes sense f I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ] # you can omit this if you're happy with English as a default locale -I18n.default_locale = :"pt" +I18n.default_locale = :pt ------------------------------------------------------- -I18n.load_path is just a Ruby Array of paths to your translation files. The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced. - === Set the locale in each request -By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en (English). +By default the I18n library will use :en (English) as a I18n.default_locale for looking up translations (if you do not specify a locale for a lookup). If you want to translate your Rails application to a single language other than English you can set I18n.default_locale to your locale. If you want to change the locale on a per-request basis though you can set it in a before_filter on the ApplicationController like this: @@ -78,13 +105,15 @@ def set_locale end ------------------------------------------------------- -This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt-BR (which is what Google also does). (TODO hints about other approaches in the resources section). +This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt (which is what Google also does). + +TIP: For other URL designs, see http://rails-i18n.org/wiki/pages/how-to-encode-the-current-locale-in-the-url[How to encode the current locale in the URL]. Now you've initialized I18n support for your application and told it which locale should be used. With that in place you're now ready for the really interesting stuff. -=== Internationalize your application +== Internationalize your application -The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application (TODO reference to wikipedia). The process of "localization" means to then provide translations and localized formats for these bits. +The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application. The process of "localization" means to then provide translations and localized formats for these bits. <<1>> So, let's internationalize something. You most probably have something like this in one of your applications: @@ -107,7 +136,9 @@ end <p><%= flash[:notice] %></p> ------------------------------------------------------- -TODO screenshot +image:images/i18n/demo_untranslated.png[rails i18n demo untranslated] + +=== Adding Translations Obviously there are two strings that are localized to English. In order to internationalize this code replace these strings with calls to Rails' #t helper with a key that makes sense for the translation: @@ -125,39 +156,66 @@ end <p><%= flash[:notice] %></p> ------------------------------------------------------- -TODO insert note about #t helper compared to I18n.t - -TODO insert note/reference about structuring translation keys - When you now render this view it will show an error message that tells you that the translations for the keys :hello_world and :hello_flash are missing. -TODO screenshot +image:images/i18n/demo_translation_missing.png[rails i18n demo translation missing] + +NOTE: Rails adds a +t+ (+translate+) helper method to your views so that you do not need to spell out +I18n.t+ all the time. Additionally this helper will catch missing translations and wrap the resulting error message into a <span class="translation_missing">. So let's add the missing translations (i.e. do the "localization" part): [source, ruby] ------------------------------------------------------- -# lib/locale/en.yml -en-US: +# config/locale/en.yml +en: hello_world: Hello World hello_flash: Hello Flash -# lib/locale/pirate.yml +# config/locale/pirate.yml pirate: hello_world: Ahoy World hello_flash: Ahoy Flash ------------------------------------------------------- -There you go. Your application now shows: +There you go. Because you haven't changed the default_locale I18n will use English. Your application now shows: + +image:images/i18n/demo_translated_english.png[rails i18n demo translated to english] -TODO screenshot +And when you change the URL to pass the pirate locale you get: + +image:images/i18n/demo_translated_pirate.png[rails i18n demo translated to pirate] + +NOTE You need to restart the server when you add new locale files. + +=== Adding Date/Time formats + +Ok, let's add a timestamp to the view so we can demo the date/time localization feature as well. To localize the time format you pass the Time object to I18n.l or (preferably) use Rails' #l helper. You can pick a format by passing the :format option, by default the :default format is used. [source, ruby] ------------------------------------------------------- -I18n.t 'store.title' -I18n.l Time.now +# app/views/home/index.html.erb +<h1><%=t :hello_world %></h1> +<p><%= flash[:notice] %></p +<p><%= l Time.now, :format => :short %></p> +------------------------------------------------------- + +And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English): + +[source, ruby] +------------------------------------------------------- +# config/locale/pirate.yml +pirate: + time: + formats: + short: "arrrround %H'ish" ------------------------------------------------------- +So that would give you: + +image:images/i18n/demo_localized_pirate.png[rails i18n demo localized time to pirate] + +NOTE Right now you might need to add some more date/time formats in order to make the I18n backend work as expected. See the http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale[rails-i18n repository] for starting points. + == Overview of the I18n API features @@ -218,7 +276,7 @@ I18n.t :missing, :default => 'Not here' If the default value is a Symbol it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned. -E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string ‘Not here’ will be returned: +E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string "Not here" will be returned: [source, ruby] ------------------------------------------------------- @@ -246,28 +304,29 @@ I18n.t 'active_record.error_messages' === Interpolation -TODO explain what this is good for +In many cases you want to abstract your translations so that variables can be interpolated into the translation. For this reason the I18n API provides an interpolation feature. All options besides :default and :scope that are passed to #translate will be interpolated to the translation: [source, ruby] ------------------------------------------------------- -I18n.backend.store_translations 'en', :thanks => 'Thanks {{name}}!' +I18n.backend.store_translations :en, :thanks => 'Thanks {{name}}!' I18n.translate :thanks, :name => 'Jeremy' # => 'Thanks Jeremy!' ------------------------------------------------------- If a translation uses :default or :scope as a interpolation variable an I18n::ReservedInterpolationKey exception is raised. If a translation expects an interpolation variable but it has not been passed to #translate an I18n::MissingInterpolationArgument exception is raised. + === Pluralization -TODO explain what this is good for +In English there's only a singular and a plural form for a given string, e.g. "1 message" and "2 messages". Other languages (http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ar[Arabic], http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ja[Japanese], http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html#ru[Russian] and many more) have different grammars that have additional or less http://www.unicode.org/cldr/data/charts/supplemental/language_plural_rules.html[plural forms]. Thus, the I18n API provides a flexible pluralization feature. The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR: [source, ruby] ------------------------------------------------------- -I18n.backend.store_translations 'en-US', :inbox => { # TODO change this +I18n.backend.store_translations :en, :inbox => { :one => '1 message', :other => '{{count}} messages' } @@ -275,7 +334,7 @@ I18n.translate :inbox, :count => 2 # => '2 messages' ------------------------------------------------------- -The algorithm for pluralizations in en-US is as simple as: +The algorithm for pluralizations in :en is as simple as: [source, ruby] ------------------------------------------------------- @@ -294,7 +353,7 @@ If no locale is passed I18n.locale is used: [source, ruby] ------------------------------------------------------- -I18n.locale = :'de' +I18n.locale = :de I18n.t :foo I18n.l Time.now ------------------------------------------------------- @@ -303,27 +362,27 @@ Explicitely passing a locale: [source, ruby] ------------------------------------------------------- -I18n.t :foo, :locale => :'de' -I18n.l Time.now, :locale => :'de' +I18n.t :foo, :locale => :de +I18n.l Time.now, :locale => :de ------------------------------------------------------- -I18n.locale defaults to I18n.default_locale which defaults to :'en'. The default locale can be set like this: +I18n.locale defaults to I18n.default_locale which defaults to :en. The default locale can be set like this: [source, ruby] ------------------------------------------------------- -I18n.default_locale = :'de' +I18n.default_locale = :de ------------------------------------------------------- == How to store your custom translations -The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. (2) +The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. <<2>> For example a Ruby Hash providing translations can look like this: [source, ruby] ------------------------------------------------------- { - :'pt-BR' => { + :pt => { :foo => { :bar => "baz" } @@ -335,18 +394,18 @@ The equivalent YAML file would look like this: [source, ruby] ------------------------------------------------------- -"pt-BR": +pt: foo: bar: baz ------------------------------------------------------- As you see in both cases the toplevel key is the locale. :foo is a namespace key and :bar is the key for the translation "baz". -Here is a "real" example from the ActiveSupport en-US translations YAML file: +Here is a "real" example from the ActiveSupport en.yml translations YAML file: [source, ruby] ------------------------------------------------------- -"en": +en: date: formats: default: "%Y-%m-%d" @@ -364,12 +423,16 @@ I18n.t :short, :scope => 'date.formats' I18n.t :short, :scope => [:date, :formats] ------------------------------------------------------- +Generally we recommend using YAML as a format for storing translations. There are cases though where you want to store Ruby lambdas as part of your locale data, e.g. for special date + === Translations for ActiveRecord models You can use the methods Model.human_name and Model.human_attribute_name(attribute) to transparently lookup translations for your model and attribute names. For example when you add the following translations: +[source, ruby] +------------------------------------------------------- en: activerecord: models: @@ -378,6 +441,7 @@ en: user: login: "Handle" # will translate User attribute "login" as "Handle" +------------------------------------------------------- Then User.human_name will return "Dude" and User.human_attribute_name(:login) will return "Handle". @@ -396,24 +460,21 @@ class User < ActiveRecord::Base end ------------------------------------------------------- -The key for the error message in this case is :blank. So ActiveRecord will first try to look up an error message with: +The key for the error message in this case is :blank. ActiveRecord will lookup this key in the namespaces: [source, ruby] ------------------------------------------------------- -activerecord.errors.messages.models.user.attributes.name.blank +activerecord.errors.messages.models.[model_name].attributes.[attribute_name] +activerecord.errors.messages.models.[model_name] +activerecord.errors.messages ------------------------------------------------------- -If it's not there it will try: +Thus, in our example it will try the following keys in this order and return the first result: [source, ruby] ------------------------------------------------------- +activerecord.errors.messages.models.user.attributes.name.blank activerecord.errors.messages.models.user.blank -------------------------------------------------------- - -If this is also not there it will use the default message from: - -[source, ruby] -------------------------------------------------------- activerecord.errors.messages.blank ------------------------------------------------------- @@ -447,28 +508,27 @@ The translated model name and translated attribute name are always available for So, for example, instead of the default error message "can not be blank" you could use the attribute name like this: "Please fill in your {{attribute}}". -Count and/or value are available where applicable. Count can be used for pluralization if present: - -[grid="all"] -`---------------------------`----------------`---------------`---------------- -validation with option message interpolation -validates_confirmation_of - :confirmation - -validates_acceptance_of - :accepted - -validates_presence_of - :blank - -validates_length_of :within, :in :too_short count -validates_length_of :within, :in :too_long count -validates_length_of :is :wrong_length count -validates_length_of :minimum :too_short count -validates_length_of :maximum :too_long count -validates_uniqueness_of - :taken value -validates_format_of - :invalid value -validates_inclusion_of - :inclusion value -validates_exclusion_of - :exclusion value -validates_associated - :invalid value -validates_numericality_of - :not_a_number value -validates_numericality_of :odd :odd value -validates_numericality_of :even :even value ------------------------------------------------------------------------------- +count and/or value are available where applicable. Count can be used for pluralization if present: + +|================================================================================== +| validation | with option | message | interpolation +| validates_confirmation_of | - | :confirmation | - +| validates_acceptance_of | - | :accepted | - +| validates_presence_of | - | :blank | - +| validates_length_of | :within, :in | :too_short | count +| validates_length_of | :within, :in | :too_long | count +| validates_length_of | :is | :wrong_length | count +| validates_length_of | :minimum | :too_short | count +| validates_length_of | :maximum | :too_long | count +| validates_uniqueness_of | - | :taken | value +| validates_format_of | - | :invalid | value +| validates_inclusion_of | - | :inclusion | value +| validates_exclusion_of | - | :exclusion | value +| validates_associated | - | :invalid | value +| validates_numericality_of | - | :not_a_number | value +| validates_numericality_of | :odd | :odd | value +| validates_numericality_of | :even | :even | value +|================================================================================== ==== Translations for the ActiveRecord error_messages_for helper @@ -479,14 +539,14 @@ Rails ships with the following translations: [source, ruby] ------------------------------------------------------- -"en": +en: activerecord: errors: template: header: one: "1 error prohibited this {{model}} from being saved" other: "{{count}} errors prohibited this {{model}} from being saved" - body: "There were problems with the following fields:" + body: "There were problems with the following fields:" ------------------------------------------------------- @@ -496,11 +556,12 @@ Rails uses fixed strings and other localizations, such as format strings and oth TODO list helpers and available keys + == Customize your I18n setup === Using different backends -For several reasons the shipped Simple backend only does the "simplest thing that ever could work" _for Ruby on Rails_ (1) ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format. +For several reasons the shipped Simple backend only does the "simplest thing that ever could work" _for Ruby on Rails_ <<3>> ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format. That does not mean you're stuck with these limitations though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend: @@ -509,30 +570,59 @@ That does not mean you're stuck with these limitations though. The Ruby I18n gem I18n.backend = Globalize::Backend::Static.new ------------------------------------------------------- -TODO expand this ...? list some backends and their features? - === Using different exception handlers -TODO +The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur: -* Explain what exceptions are raised and why we are using exceptions for communication from backend to frontend. -* Explain the default behaviour. -* Explain the :raise option +[source, ruby] +------------------------------------------------------- +MissingTranslationData # no translation was found for the requested key +InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil) +InvalidPluralizationData # a count option was passed but the translation data is not suitable for pluralization +MissingInterpolationArgument # the translation expects an interpolation argument that has not been passed +ReservedInterpolationKey # the translation contains a reserved interpolation variable name (i.e. one of: scope, default) +UnknownFileType # the backend does not know how to handle a file type that was added to I18n.load_path +------------------------------------------------------- + +The I18n API will catch all of these exceptions when they were thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for MissingTranslationData exceptions. When a MissingTranslationData exception has been caught it will return the exception’s error message string containing the missing key/scope. + +The reason for this is that during development you'd usually want your views to still render even though a translation is missing. + +In other contexts you might want to change this behaviour though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module: -* Example 1: the Rails #t helper uses a custom exception handler that catches I18n::MissingTranslationData and wraps the message into a span with the CSS class "translation_missing" -* Example 2: for tests you might want a handler that just raises all exceptions all the time -* Example 3: a handler +[source, ruby] +------------------------------------------------------- +module I18n + def just_raise_that_exception(*args) + raise args.first + end +end + +I18n.exception_handler = :just_raise_that_exception +------------------------------------------------------- + +This would re-raise all caught exceptions including MissingTranslationData. + +Another example where the default behaviour is less desirable is the Rails TranslationHelper which provides the method #t (as well as #translate). When a MissingTranslationData exception occurs in this context the helper wraps the message into a span with the css class translation_missing. + +To do so the helper forces I18n#translate to raise exceptions no matter what exception handler is defined by setting the :raise option: + +[source, ruby] +------------------------------------------------------- +I18n.t :foo, :raise => true # always re-raises exceptions from the backend +------------------------------------------------------- == Resources -* http://rails-i18n.org == Footnotes -(1) One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions. +[[[1]]] Or, to quote http://en.wikipedia.org/wiki/Internationalization_and_localization[Wikipedia]: _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_ + +[[[2]]] Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files. -(2) Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files. +[[[3]]] One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions. == Credits diff --git a/railties/doc/guides/source/images/i18n/demo_localized_pirate.png b/railties/doc/guides/source/images/i18n/demo_localized_pirate.png Binary files differnew file mode 100644 index 0000000000..22b93416a0 --- /dev/null +++ b/railties/doc/guides/source/images/i18n/demo_localized_pirate.png diff --git a/railties/doc/guides/source/images/i18n/demo_translated_en.png b/railties/doc/guides/source/images/i18n/demo_translated_en.png Binary files differnew file mode 100644 index 0000000000..7ea0c437a5 --- /dev/null +++ b/railties/doc/guides/source/images/i18n/demo_translated_en.png diff --git a/railties/doc/guides/source/images/i18n/demo_translated_pirate.png b/railties/doc/guides/source/images/i18n/demo_translated_pirate.png Binary files differnew file mode 100644 index 0000000000..60ef370158 --- /dev/null +++ b/railties/doc/guides/source/images/i18n/demo_translated_pirate.png diff --git a/railties/doc/guides/source/images/i18n/demo_translation_missing.png b/railties/doc/guides/source/images/i18n/demo_translation_missing.png Binary files differnew file mode 100644 index 0000000000..86a3121cc1 --- /dev/null +++ b/railties/doc/guides/source/images/i18n/demo_translation_missing.png diff --git a/railties/doc/guides/source/images/i18n/demo_untranslated.png b/railties/doc/guides/source/images/i18n/demo_untranslated.png Binary files differnew file mode 100644 index 0000000000..e6717fb7d1 --- /dev/null +++ b/railties/doc/guides/source/images/i18n/demo_untranslated.png diff --git a/railties/doc/guides/source/testing_rails_applications.txt b/railties/doc/guides/source/testing_rails_applications.txt index b492fdb300..cb77829fc1 100644 --- a/railties/doc/guides/source/testing_rails_applications.txt +++ b/railties/doc/guides/source/testing_rails_applications.txt @@ -226,18 +226,18 @@ Above +rake db:migrate+ runs any pending migrations on the _developemnt_ environ NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists. -==== Rake Tasks for Preparing you Application for Testing == +==== Rake Tasks for Preparing your Application for Testing ==== [grid="all"] ------------------------------------------------------------------------------------- -Tasks Description ------------------------------------------------------------------------------------- -+rake db:test:clone+ Recreate the test database from the current environment's database schema -+rake db:test:clone_structure+ Recreate the test databases from the development structure -+rake db:test:load+ Recreate the test database from the current +schema.rb+ -+rake db:test:prepare+ Check for pending migrations and load the test schema -+rake db:test:purge+ Empty the test database. ------------------------------------------------------------------------------------- +|------------------------------------------------------------------------------------ +|Tasks Description +|------------------------------------------------------------------------------------ +|+rake db:test:clone+ Recreate the test database from the current environment's database schema +|+rake db:test:clone_structure+ Recreate the test databases from the development structure +|+rake db:test:load+ Recreate the test database from the current +schema.rb+ +|+rake db:test:prepare+ Check for pending migrations and load the test schema +|+rake db:test:purge+ Empty the test database. +|------------------------------------------------------------------------------------ TIP: You can see all these rake tasks and their descriptions by running +rake \-\-tasks \-\-describe+ |