Recent notes
RSS feed
Required Reading
The details for using layout (such as possible values for the conditions hash) can be found in ActionController::Layout::ClassMethods.

Convert strings to Dates
Uses the undocumented Date._parse method. Some usage examples:
'06/15/2008'.to_date # => Sun, 15 Jun 2008 '20080615'.to_date # => Sun, 15 Jun 2008 '2008-06-15'.to_date # => Sun, 15 Jun 2008 'Sun, 15 Jun 2008'.to_date # => Sun, 15 Jun 2008

migration example
def self.up create_table :regs do |t|
t.column :login, :string, :limit=>'10' t.column :pass, :string, :limit=>'10' t.column :email, :string, :limit=>'20' t.column :fio, :string, :limit=>'30' t.column :born, :date t.column :phone_code, :integer, :limit=>'3' t.column :phone_post, :integer, :limit=>'7' t.column :password, :string, :limit=>'20' t.column :pass_when, :date t.column :pass_who, :string,:limit=>'30' t.column :wmid, :integer, :limit=>12 t.column :wmr, :integer, :limit=>12 t.column :wmz, :integer, :limit=>12 end
add_index :regs, [:login, :wmr, :wmz], :unique => true end


watch out for urls with &
image_tag(‘x.com/aaa?a=1&b=2’) = x.com/aaa?a=1&b=2

For more information
See Base class.

For more information
See ActiveMailer::Base.

List of statuses
You can view a full list of statuses at http://dev.rubyonrails.org/browser/trunk/actionpack/lib/action_controller/status_codes.rb.
head can be called with a symbol or a status code:
Using head with a symbol
head :length_required # 411 Length Required head :ok # 200 OK
Using head with a status code
head 404 # 404 Not Found

Using counters with collections
When you’re rendering a collection partial, the partial_name_counter variable contains the position of the current element in the collection. For example:
<%= render(:partial => 'example', :collection => %w(rails-doc is cool)) %>
Now in _example.html.erb:
<p>Element: <%= example %> (index: <%= example_counter %>)</p>
It would produce:
<p>Element: rails-doc (index: 1)</p> <p>Element: is (index: 2)</p> <p>Element: cool (index: 3)</p>
As you can see, indexing starts from 1.

Link to same URL with different format
Use params.merge as options. Ex.
<%= link_to "RSS feed", params.merge(:format => :rss), :class => "feed_link" %>

Using a specific layout
To choose the layout (or no layout) for a method call the render method with a :layout option.

around_filter code example
This is how it’s used:
around_filter do |controller, action| do_your(:stuff) do action.call end end

Add if before Ajax.request
Use link_to_remote’s before
link_to_remote(“watcher”, {:url => “/watchers/add”, :before => “if($F(‘user_id’)==”){return false;}” })
<a onclick=“if($F(‘user_id’)==”){return false;}; new Ajax.Request(‘/watchers/add’, {asynchronous:true, evalScripts:true, parameters:”}); return false;”>添加订阅人

Add empty option and text is -select-
select :object, :method, options, :prompt => ‘-select-’


Getting textfield values into "link_to_remote" via Javascript Prototype
Use Prototype to get the value of a text field via Javascript, to pass to the ‘link_to_remote’ helper using code similar to below:
link_to_remote 'Link Name', {:update => "foo", :url => {:controller => "bar", :action => "baz"}, :with => "'model[textfield]=' + $F('textfield_id')"}

Connections to multiple databases
establish_connection can be used to connect to multiple databases. The immediate downside is that your rake migrations may not work properly without hacking.
In each model that resides in a different database we call:
establish_connection :different_database
You can check they are working by hitting script/console with:
>> App.connection.instance_eval {@config[:database]} => "app_development" >> AnotherDatabase.connection.instance_eval {@config[:database]} => "another_database"
Now doing a call to AnotherDatabase.find() will connect to the AnotherDatabase database and start returning results.

error in block code example
I guess there’s an error in this part of the code:
link_to_function("Show me more", nil, :id => "more_link") do |page| page[:details].visual_effect :toggle_blind page[:more_link].replace_html "Show me less" end
It doesn’t work. It should be:
link_to_function("Show me more", nil, :id => "more_link") do |page| page[:details].toggle "Blind" page[:more_link].replace_html "Show me less" end
Using Rails 2.1.0

Rails 2.1 caching internals
Rails 2.1 caching features are pretty much undocumented. Rob Anderton has documented some internal stuff here:
http://www.thewebfellas.com/blog/2008/6/9/rails-2-1-now-with-better-integrated-caching

benchmark and silence methods
benchmark (title, log_level = Logger::DEBUG, use_silence = true) {|| …}
Log and benchmark the workings of a single block and silence whatever logging that may have happened inside it (unless use_silence is set to false).
The benchmark is only recorded if the current level of the logger matches the log_level, which makes it easy to include benchmarking statements in production software that will remain inexpensive because the benchmark will only be conducted if the log level is low enough.
silence () {|| …}
Silences the logger for the duration of the block. To silence the logger in your controller, simply use:
NameOfController.logger.silence do
# your code here...
end

:case_sensitive is on by default?
In contrast to what the documentation said, :case_sensitive seems to be on by default. This is the case with MySQL at least, I’m not sure about other databases.


Better explanation for ActionController sweepers
The first sentence in this description is confusing. http://codelevy.com/articles/2008/03/04/rails-caching-sweepers-controllers-and-models explains it more clearly.

Use the :as option for SEO friendly URLs
The :as option to map.resources can be used to generate SEO friendly URLs like so:
Code Example
map.resources :operating_systems, :as => 'operating-systems' # operating_systems_path => /operating-systems

Turns hash keys into symbols
This method is part of ActiveSupport, which is a collection of classes and standard library extensions that are useful for Rails.
symbolize_keys! returns a new hash with all keys converted to symbols.
This can be helpful when you have a non-ActiveRecord model and you want your initialize method to take a hash of parameters. If you symbolize the hash, you can extract your parameters regardless of whether initialize received a hash of strings or hash of symbols.

Passing find() arguments
I you need to pass additional arguments to a scope (e.g. limit), do this:
Shirt.colored('red').all(:limit => 10)

Rails defined Mime Types
Here are all the default Rails Mime Types:
"*/*" => :all "text/plain" => :text "text/html" => :html "application/xhtml+xml" => :html "text/javascript" => :js "application/javascript" => :js "application/x-javascript" => :js "text/calendar" => :ics "text/csv" => :csv "application/xml" => :xml "text/xml" => :xml "application/x-xml" => :xml "text/yaml" => :yaml "application/x-yaml" => :yaml "application/rss+xml" => :rss "application/atom+xml" => :atom "application/json" => :json "text/x-json" => :json

Default Mime Types
This module sets up all the default mime-types. Here they are:
"*/*" => :all "text/plain" => :text "text/html" => :html "application/xhtml+xml" => :html "text/javascript" => :js "application/javascript" => :js "application/x-javascript" => :js "text/calendar" => :ics "text/csv" => :csv "application/xml" => :xml "text/xml" => :xml "application/x-xml" => :xml "text/yaml" => :yaml "application/x-yaml" => :yaml "application/rss+xml" => :rss "application/atom+xml" => :atom "application/json" => :json "text/x-json" => :json

x-sendfile
Rails 2.1 supports the x_sendfile apache module:
send_file '/path/to.png', :x_sendfile => true, :type => 'image/png'