Good notes posted to Ruby on Rails
RSS feed:use_route to force named routes in url_for
If you are using a plugin or library that calls url_for internally, you can force it to use a particular named route with the :use_route key. For instance, calling:
url_for(:controller => 'posts', :action => 'view', :id => post, :use_route => :special_post)
will have the same effect as:
special_post_url(post)
Naturally, this is much more verbose if you’re calling it directly, but can be a lifesaver if url_for is being called inside another method (e.g. will_paginate).
Re: Using a Loading Graphic
You probably want to be using :complete, not :loaded, to execute Javascript when an Ajax request has finished. See: http://prototypejs.org/api/ajax/options
Common options
“Common options” mentioned here is default PrototypeHelper options documented in link_to_remote
This means you can use :loading, :loaded, :failure, :success, etc in observe_field.
Add spacer template
<%= render :partial => “product”, :collection => @products, :spacer_template => “product_ruler” %>
current_url
exact url from browser window:
def current_url url_for :only_path=>false,:overwrite_params=>{} end
Can be extended but only with a module
Although not documented, belongs_to does support Association Extensions however it doesn’t accept a block like has_many does. So you can’t do this:
class Account < ActiveRecord::Base belongs_to :person do def do_something_funky # Some exciting code end end end
but you can do this:
module FunkyExtension def do_something_funky # Some exciting code end end class Account < ActiveRecord::Base belongs_to :person, :extend => FunkyExtension end
And then call it like this:
@account = Account.first @account.person.do_something_funky
A work-around for adding confirmation to image_submit_tag
Sometimes you may want to add a confirmation to image submit tags but this function does not allow it. To get over this limitation use a normal submit tag and set the src and type properties (set type to “image”)
Code example
submit_tag “Delete”, :confirm => “Are you sure?”, :src => “/images/trash.png”, :type => “image” %>
Also for numeric
1.humanize == “1″ 1000000.humanize == “1.000.000″ 1000.12345.humanize == “1.000,12″
http://pragmatig.wordpress.com/2008/10/25/numbers-for-humans-humanize-for-numeric/
Prompt vs. Select
According to the docs in form_options_helper.rb
:include_blank - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element.
:prompt - set to true or a prompt string. When the select element doesn’t have a value yet, this prepends an option with a generic prompt – “Please select” – or the given prompt string.
The main difference is that if the select already has a value, then :prompt will not show whereas the :include_blank always will.
Back it up with a unique index
As mentioned briefly above, as well as using this validation in your model you should ensure the underlying database table also has a unique index to avoid a race condition.
For example:
class User < ActiveRecord::Base validates_uniqueness_of :login_name end
The index can be specified in the migration for the User model using add_index like this:
add_index :users, :login_name, :unique => true
You do a similar thing when using the :scope option:
class Person < ActiveRecord::Base validates_uniqueness_of :user_name, :scope => :account_id end
Should have a migration like this:
add_index :people, [ :account_id, :user_name ], :unique => true
Note that both the attribute being validated (:user_name) and the attribute(s) used in the :scope (:account_id) must be part of the index.
For a clear and concise explanation of the potential for a race condition see Hongli Lai’s blog.
Customizing attribute names in error messages
By default, the error messages translate the names of the attributes through String#humanize. The way to to change that is to override the ActiveRecord::Base.human_attribute_name method.
For example, if you want to name a column in your database as :www_url and you want to say “Website” instead of “Www url” in the error message, you can put this into your model:
class Person < ActiveRecord::Base def self.human_attribute_name(attribute_key_name) if attribute_key_name.to_sym == :www_url "Website" else super end end end
Currently this seems to be the cleanest and easiest way. Unfortunately, human_attribute_name is deprecated and may stop working in a future release of Rails.
Gotcha when defining :finder_sql or :counter_sql
When setting custom SQL statements in the :finder_sql or :counter_sql queries, if you need to inject attributes from the current object, such as the ID, make sure to disable string interpolation of the statement by using single quotes or %q().
Example:
has_many :relationships, :class_name => 'Relationship', :finder_sql => %q( SELECT DISTINCT relationships.* FROM relationships WHERE contact_id = #{id} )
Surrounding this SQL with double-quotes or %Q() will expand #{id} too early, resulting in a warning about Object#id being deprecated and general brokenness.
Using a Loading Graphic
If you want to make a little loading graphic, typically you use an animated gif (like a little spinner or something). Both link_to_remote and remote_form_for allow you to easily do this by using the :loaded and :loading triggers to call javascript.
For example:
<% remote_form_for @survey, :loading => "$('loading').show();", :loaded => "$('loading').hide();" do |f| %> <%= submit_tag ' Save' %> <%= image_tag "indicator_circle.gif", :style => 'display: none;', :id => 'loading' %> <% end %>
The ‘loading’ parameter used for the ‘$’ prototype selector is the id of the animated gif. It starts out hidden, and is toggled by the loading/loaded triggers.
Opening a link in a new window
Use “_blank”, not “_new” to open a link in a new window.
link_to "External link", "http://foo.bar", :target => "_blank" # => <a href="http://foo.bar" target="_blank">External link</a>
List of status codes and their symbols
Note that the :status option accepts not only an HTTP status code (such as 500), but also a symbol representing that code (such as :created), if that makes more sense to you. Here’s a list of which symbols map to which numbers (derived from ActionController::StatusCodes::SYMBOL_TO_STATUS_CODE):
100 = :continue 101 = :switching_protocols 102 = :processing 200 = :ok 201 = :created 202 = :accepted 203 = :non_authoritative_information 204 = :no_content 205 = :reset_content 206 = :partial_content 207 = :multi_status 226 = :im_used 300 = :multiple_choices 301 = :moved_permanently 302 = :found 303 = :see_other 304 = :not_modified 305 = :use_proxy 307 = :temporary_redirect 400 = :bad_request 401 = :unauthorized 402 = :payment_required 403 = :forbidden 404 = :not_found 405 = :method_not_allowed 406 = :not_acceptable 407 = :proxy_authentication_required 408 = :request_timeout 409 = :conflict 410 = :gone 411 = :length_required 412 = :precondition_failed 413 = :request_entity_too_large 414 = :request_uri_too_long 415 = :unsupported_media_type 416 = :requested_range_not_satisfiable 417 = :expectation_failed 422 = :unprocessable_entity 423 = :locked 424 = :failed_dependency 426 = :upgrade_required 500 = :internal_server_error 501 = :not_implemented 502 = :bad_gateway 503 = :service_unavailable 504 = :gateway_timeout 505 = :http_version_not_supported 507 = :insufficient_storage 510 = :not_extended
Implemented in database adapters
These methods are not implemented in the abstract classes. Instead, all database adapters implement these separately, if the feature is supported.
Rendering nothing
If your controller action does not explicitly call render, Rails will, by default, attempt to locate and render the template corresponding to the action. It’s not uncommon, for example with Ajax calls, to want to render nothing. This will circumvent the default rendering and prevent errors on missing templates. To render nothing simply do the following:
render :nothing => true
Its important to note that this isn’t the same as returning no HTTP response. In fact, this results in an HTTP response with a status code of 200 OK being sent back with a blank content body. Why does it matter? Well, you can still test your controller by asserting that a :success response was returned.
Seriously! Do not forget the brackets
thank you source jamesandre.ws
the form_for([:admin, @user]) must have the [] brackets to avoid errors like “Only get requests are allowed”
<% form_for([:admin, @user]) do |f| %> <%= render :partial => 'form' %> <%= submit_tag "Create" %> <% end %>
More on deprecation
This is not deprecated. I think the docs are confused because the validate, validate_on_create, and validate_on_update methods are actually callbacks and not explicitly defined on their own. The correct usage is the same as in the docs above.
:prefix option
Be aware!
By default, if you do select_month(Date.today, :field_name => ‘start’) it will generate select tag with name “date[start]”. If you want it to be something other than date[], add :prefix option, like this:
select_month(Date.today, :field_name => 'start', :prefix => 'timer')
This will render select tag with name “timer[start]”.
Taken from sources of name_and_id_from_options method.
Link to caller URL
link_to “Back”, :back
Documentation for Associations
You are most likely looking for ActiveRecord::Associations::ClassMethods
If you're not using resource
If you don’t use resource for your remote_form_for, then :url option is necessary.
For example:
<% remote_form_for "not_resource" do |f| ... %>
won’t work. But with :url option, it will:
<% remote_form_for "not_resource", :url => { :controller => "recommend", :action => "send" } do ... %>
has_one Nesting in Rails 2.0
Routers:
map.resources :user, :has_one => [:avatar]
Views:
form_for [@user, @avatar], :url => user_avatar_url(@user) do |f| ... end
Pass the observed fields value as a parameter in the Ajax request
Use encodeURIComponent with with to pass an encoded value as a parameter (POST or GET) of the AJAX request. For example:
<%= observe_field :company_id,
:url => {:action => ‘facilities’, :only_path => false}, :with => “‘company=’ + encodeURIComponent(value)” %> Also, setting only_path => false for the URL ensures that the full URL (including host and protocol) is used for the AJAX request.
Example of composed_of composition class implementation
If we have following code in model:
composed_of :temperature, :mapping => %w(celsius)
Then our composition class can be this:
class Temperature def initialize(celsius) @celsius = celsius end # This method is called by ActiveRecord, when record is saved. # Result of this method will be stored in table in "celsius" field, # and later when the record is loaded again, this will go to # our Temperature#new constructor. def celsius @celsius end # This is example of method that we can add to make this composition useful. def farenheit @celsius * 9/5 + 32 end end
has_many :through
It’s is recommended to use has_many :through association instead of has_and_belongs_to_many. has_many :through is better supported and generally easier to work with once you grasp the idea.
Compare old and new form for
Old form for
<% form_for :user, :url => users_path do %> <%= render :partial => 'form' %> <%= submit_tag 'Create' %> <% end %>
New form for
<% form_for(@user) do |f| %> <%= render :partial => f %> <%= submit_tag 'Create' %> <% end %>
All methods
create_table :table do |t|
t.column # adds an ordinary column. Ex: t.column(:name, :string) t.index # adds a new index. t.timestamps t.change # changes the column definition. Ex: t.change(:name, :string, :limit => 80) t.change_default # changes the column default value. t.rename # changes the name of the column. t.references t.belongs_to t.string t.text t.integer t.float t.decimal t.datetime t.timestamp t.time t.date t.binary t.boolean t.remove t.remove_references t.remove_belongs_to t.remove_index t.remove_timestamps end
All methods
change_table :table do |t|
t.column # adds an ordinary column. Ex: t.column(:name, :string) t.index # adds a new index. t.timestamps t.change # changes the column definition. Ex: t.change(:name, :string, :limit => 80) t.change_default # changes the column default value. t.rename # changes the name of the column. t.references t.belongs_to t.string t.text t.integer t.float t.decimal t.datetime t.timestamp t.time t.date t.binary t.boolean t.remove t.remove_references t.remove_belongs_to t.remove_index t.remove_timestamps end


