Flowdock

Good notes posted to Ruby on Rails

RSS feed
October 15, 2008
29 thanks

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
October 10, 2008
8 thanks

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.

October 9, 2008 - (<= v2.1.0)
12 thanks

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.

October 8, 2008
3 thanks

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 %>
October 7, 2008 - (v2.0.3 - v2.1.0)
4 thanks

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.

October 2, 2008
10 thanks

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

October 1, 2008
5 thanks
September 30, 2008
5 thanks

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 ... %> 
September 28, 2008 - (<= v2.1.0)
3 thanks

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
September 26, 2008 - (v1.2.6 - v2.1.0)
5 thanks

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.

September 26, 2008
4 thanks

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
September 25, 2008
4 thanks

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.

September 25, 2008 - (v2.1.0)
3 thanks

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 %>
September 25, 2008
22 thanks

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
September 25, 2008
18 thanks

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
September 25, 2008
6 thanks

Expressions in the sum method

Person.sum(“2 * age”)

Person.sum(:age, :conditions=>'1 = 2')
September 23, 2008 - (<= v2.1.0)
3 thanks

Method description from Rails 2.0

If text is longer than length, text will be truncated to the length of length (defaults to 30) and the last characters will be replaced with the truncate_string (defaults to “…”).

Examples

truncate("Once upon a time in a world far far away", 14)
# => Once upon a...

truncate("Once upon a time in a world far far away")
# => Once upon a time in a world f...

truncate("And they found that many people were sleeping better.", 25, "(clipped)")
# => And they found that many (clipped)

truncate("And they found that many people were sleeping better.", 15, "... (continued)")
# => And they found... (continued)
September 19, 2008 - (v2.1.0)
3 thanks

:expires_in option

If you need :expires_in functionality in Rails 2.1, you can use this plugin:

http://github.com/nickpad/rails-caches-action-patch/tree/master

September 17, 2008
4 thanks

Turn layout off with render

Thats awkward, but the code below does not turn layout off:

render :action => "short_goal", :layout => nil

you must use false

render :action => "short_goal", :layout => false
September 16, 2008
8 thanks

print standard-looking messages during migration

Within a migration file you can use the say_with_time method to print out informational messages that match the style of standard migration messages. See the say method also.

say_with_time "migrate existing data" do
  # ... execute migration sql ...
end
#=> "-- migrate existing data"
#=> "   -> 0.0299s"
September 15, 2008
4 thanks

:null => false

To not allow a column to have a NULL value, pass :null => false. Seems silly, but that’s it.

September 15, 2008 - (<= v2.1.0)
8 thanks
September 11, 2008 - (<= v2.1.0)
4 thanks

Information on 'ModelName.transaction'

If you are looking for information about:

ModelName.transaction do
  ...
end

or

transaction do
  ...
end

see ActiveRecord::Transactions::ClassMethods

September 11, 2008 - (<= v2.1.0)
4 thanks

Information on 'ModelName.transaction'

If you are looking for information about:

ModelName.transaction do
  ...
end

or

transaction do
  ...
end

see ActiveRecord::Transactions::ClassMethods

September 10, 2008
4 thanks

Be careful with overriding dynamic attribute based finders

don’t try something like this:

class Foo < ActiveRecord::Base
  def self.find_by_bar(*args)
    foo = super(*args)
    raise SomeCustomException unless foo
    foo
  end
end

In newer versions of rails, method_missing defines find_by_bar when you first use it. By calling super, you’re triggering method_missing and overwriting your custom definition! It will work the first time then break! Manually write the call to find!

September 9, 2008 - (<= v2.1.0)
4 thanks

Reset a form

To reset a form easily you can do the following:

page["formid"].reset
September 5, 2008
6 thanks

Custom collection local variable name

Regarding the previous note from hoodow about using :variable_name to create a custom local variable name when rendering a collection with a partial, the argument should be :as instead of :variable_name, so:

render :partial => “video_listing”, :collection => @recommendations, :as => :video

September 5, 2008 - (v1.0.0 - v2.0.3)
3 thanks

This method has moved

To help anyone else looking, this method is now on the ActionView::Template class.

September 4, 2008
5 thanks

Testing protected controllers

When testing controllers which are protected with #authenticate_or_request_with_http_basic this is how you can supply the credentials for a successful login:

@request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")

Must be set before the request is sent through #get or whatever method.