Notes posted to Ruby on Rails

RSS feed
July 8, 2010 - (>= v2.1.0)
1 thank

Rails v2.1.0 has built-in time-zone support

Rails versions as of 2.1.0 have basic timezone support built-in to the Time object. However, to get a list of all the timezones you need to install the tzinfo gem.


All contries, all timezones:

TZInfo::Country.all.sort_by { |c| c.name }.each do |c|
  puts c.name # E.g. Norway
  c.zones.each do |z|
    puts "\t#{z.friendly_identifier(true)} (#{z.identifier})" # E.g. Oslo (Europe/Oslo)

TZInfo::TimeZone.get(identifier) returns a TimeZone -object by the identifier.

July 4, 2010
2 thanks

Common use

I typically use require_dependency when developing a class or module that resides in my rails app, perhaps in the lib/ dir. A normal require statement does not reload my changes, so I use require_dependency in files that reference my newly developed class or module.

July 2, 2010
0 thanks

Takes array

Like assert_difference this method can take an array of expressions to evaluate all of them. For example:

assert_no_difference ['Publisher.count', 'User.count', 'Membership.count'] do
  post :create

It creates an assertion for each item in the array. So this will add three assertions to your test.

June 24, 2010
0 thanks


<div style=“margin:0;padding:0”>

<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" /> 


Helper generates a div element with a hidden input inside. This is a security feature of Rails called cross-site request forgery protection and form helpers generate it for every form whose action is not “get”.

June 23, 2010
0 thanks

Getting the client ip

From CgiRequest you can get the client ip in controller:

June 23, 2010
2 thanks

Accessing controller data

You can access controller attributes from views via the @controller variable.

It has some important attributes:

  • @controller.controller_name -> the name of the controller

  • @controller.request -> returns the ActionController::Request

    • @controller.request.method -> the request method ( get, post, put, delete )

    • @controller.request.host -> the request host ( ip address or hostname ) where your server runs

    • @controller.request.ip -> the ip where your browser runs

June 23, 2010
1 thank

how I use it

def rescue_action_in_public(exception)

case exception

when ActiveRecord::RecordNotFound, ActionController::UnknownAction, ActionController::RoutingError
  redirect_to errors_path(404), :status=>301
  redirect_to errors_path(500)


June 18, 2010
8 thanks

multiple attributes with the same validations

You can list multiple attributes if they share the same validations

validates :title, :body, :presence => true

sending the attributes as an array will return an error

validates [:title, :body], :presence => true
#=> ArgumentError: Attribute names must be symbols
June 18, 2010
0 thanks

Careful when updating foreign key directly

Seems when you change key directly it doesn’t update association automatically.

>> chicken = Chicken.first
>> chicken.head
=> old_head
>> chicken.head_id = new_head.id
>> chicken.head
=> old_head

Easy (stupid?) way to fix it:

class Chicken
  def head_id=(value)
    self.head = Head.find_by_id(value)
June 13, 2010 - (>= v2.3.8)
0 thanks

Positioning the column. MySQL only

Add support for MySQL column positioning via #add_column and #change_column

add_column and change_column in the MySQL adapter now accept some additional options:

:first => true # Put the column in front of all the columns

:after => column_name # Put the column after ‘column_name’

class AddLastNameToUsers < ActiveRecord::Migration
  def self.up
    add_column :users, :last_name, :after => :first_name

  def self.down
    remove_column :users, :last_name


class AddIdToUsers < ActiveRecord::Migration
  def self.up
    add_column :urers, :id, :first => true

  def self.down
    remove_column :users, :id
June 7, 2010
2 thanks

No security

One important thing to remember is that this is NOT hidden in the source code and can be modified by an evil user so all input in a hidden field should be considered as untrustworthy and checked just like a visible field.

June 4, 2010
2 thanks

database exceptions will still be raised

Note that save() only returns false on validation errors (when valid? returns false). If other errors occur at the database level, like a database deadlock or trying to insert null into a column that doesn’t allow it, that will still raise an exception.

May 31, 2010
4 thanks

Naming fragment cache

One of the common ways of using fragment caching is to cache content that’s shared across the site (eg. left navigation, menus, widgets etc.) that looks and works the same regardless of the name of the action or controller calling it. In such cases it’s very easy to just use named fragment caching eg.:

<% cache('left_nav') do -%>
  <%= display_left_nav -%>
<% end -%>
May 27, 2010
2 thanks

Use :path_prefix for the namespace

Resources are added after the :path_prefix. However if you use a :path_prefix on a resource, it overrides the namespace path instead of appending to it (as I think it should).

Here is what I wrote to create a versioned API access path.

map.namespace :api3, :path_prefix=>"/api/v3" do |api|
  api.resources :posts
  api.resources :comments, :path_prefix=>"/api/v3/post/:post_id"

This will create routes like

path: /api/v3/posts/1 
named_route: api3_post()
May 26, 2010
0 thanks

Prevent transactional fixtures for a specific test class

If you want to prevent a specific group of tests from being run inside a transaction, just define inside your test class the methods teardown_fixtures and setup_fixtures with empty bodies.

May 26, 2010
0 thanks

Prevent transactional fixtures for a specific suite

If you want to prevent a specific group of tests from being run inside a transaction, just define inside your test class the methods teardown_fixtures and setup_fixtures with empty bodies.

May 18, 2010
2 thanks

How using Array methods

It’s not possible to use Array methods with a scope because it’s not an Array but an ActiveRecord::NamedScope::Scope :



doesn’t run.

But you can use the to_a method to transform the ActiveRecord::NamedScope::Scope to an Array :

May 14, 2010
0 thanks

You must use the yielded object

A warning note (at least for v2.3.4): if you don’t use the yielded format object, you will get a cryptic error like this:

NoMethodError (You have a nil object when you didn't expect it!
The error occurred while evaluating nil.call):
 app/controllers/comments_controller.rb:11:in `create'

So make sure you use it!

May 11, 2010
1 thank

No Layout, other options

While it renders to the same rules as render, you need to specify params.

You’d think this would work:

render_to_string "users/profile", :layout => false

You need to do this instead

render_to_string(:layout => "users/profile", :layout => false)
May 6, 2010
1 thank


Be aware that has_and_belongs_to_many saves association to join table immediately after assign. It does NOT wait for my_object.save. Hence if save does not get through validations (or fail for any other reason), associated records will still be in the database.

Here is a nice workaround: http://github.com/TylerRick/has_and_belongs_to_many_with_deferred_save

May 4, 2010
0 thanks

Be careful about ActiveRecord::Base.include_root_in_json

If you have set ActiveRecord::Base.include_root_in_json = true, then when you do .to_json on an object, the output will begin with the class name rather than just a hash of attributes.

from the rails docs

konata = User.find(1)
ActiveRecord::Base.include_root_in_json = true
=> { "user": {"id": 1, "name": "Konata Izumi", "age": 16,
          "created_at": "2006/08/01", "awesome": true} }

if you try to pass this output as the argument to from_json, things will blow up.

User.new.from_json(konata.to_json[“user”]) will just pass in the attribute hash and will work.

Also, note that if you’ve use attr_accessible to limit mass assignment, you’ll have problems if you try pass in attributes that are not allowed to be mass assigned.

April 27, 2010
0 thanks

smtp syntax error 555 5.5.2

If You’re seeing a Net::SMTPFatalError (555 5.5.2 Syntax error ...) than You should check the email’s from header ! You probably have brackets while calling the from attribute setter :

Works in Rails < 2.3.3

def signup_notification(recipient)
  recipients      recipient.email_address_with_name
  subject         "New account information"
  from            %("My App" <no-reply@myapp.com>)

Works in Rails 2.3.5

def signup_notification(recipient)
  recipients      recipient.email_address_with_name
  subject         "New account information"
  from            'no-reply@myapp.com' # no <> brackets !

in Rails 2.3.3 the from email address will get wrapped with angle brackets, thus it must not have them within the address.

April 25, 2010
0 thanks

Avoid DoubleRenderError

One can not invoke render twice during an action. Thus if You have a complicated rendering logic but at the end would like to render some default content, or just would like to find out whether render has been called during the current action, use performed?. This also works with “empty” renderings such as head.

April 24, 2010
0 thanks

Rendering After Exception In respond_to() Block

Remember, format blocks set the response’s content type. This can present problems when handling errors.

class MediaController
  rescue_from  ActionController::MissingFile do |e|
    # User's browser probably wont display this 
    # Content-Type is application/x-shockwave-flash
    render :file => File.join(Rails.public_path, '404.html'), :status => 404 

  # show details or stream video
  def show
    @media = Media.find params[:id]
    respond_to do |format|
      format.flv { send_file @media.path, :disposition => 'inline' }

For these situations you must set :content_type when calling render:

render :file => File.join(Rails.public_path, '404.html'), :status => 404, :content_type => 'text/html' 
April 22, 2010
1 thank

Dynamic exists? methods

There are no dynamic exists? methods analogous to dynamic finders, which means that while you can do this:


you can’t do this:

Person.exists_by_name('David') # DOES NOT WORK

nor this:

Person.exists_by_name?('David') # DOES NOT WORK

However, you can simulate this with dynamic scope:


You’ll have to admit that this is so much better than the plain old method:

Person.exists?(:name => "David")
April 22, 2010
1 thank

nil Argument Raises An I18n::ArgumentError

You might want to do this:

module ActionView
 module Helpers
   module TranslationHelper
     def localize(*args)
       #Avoid I18n::ArgumentError for nil values
       I18n.localize(*args) unless args.first.nil?
     # l() still points at old definition
     alias l localize


April 20, 2010
2 thanks

Does not work with polymorphic relations

If you have polymorphic relations, e.g.:

class Bookmark < ActiveRecord::Base
  belongs_to :thing, :polymorphic => true
  belongs_to :owner, :polymorphic => true

and you want to ensure that a thing can bookmarked by an owner at most once, you can’t do this:

validates_uniqueness_of :thing, :scope => :owner

Instead, you must use the real column names, e.g.:

validates_uniqueness_of :thing_id, :scope => [:thing_type, :owner_id, :owner_type]
April 9, 2010
2 thanks

The :method goes in the :html option

When using a restful form helper and you want to use a method other than POST, remember to put the :method in the :html option.

e.g. To send a DELETE request instead of the usual POST (with a nested resource thrown in for good measure) use:

<% form_for [@post, @comment], :html => { :method => :delete } do |f| -%>
April 3, 2010
0 thanks

:autosave => false vs. :autosave => nil

The documentation above mentions that :autosave => true always saves the association and that it’s “off” by default. What it doesn’t mention what they mean by “off”.

  • :autosave => nil (the default “off” behavior) will still autosave the association if it has changed or is a new record.

  • :autosave => false seems to prevent autosaving of the association, even if it has changed.

I’ve found :autosave => false to be useful behavior when trying to prevent cyclical dependency loops; there are likely other useful use cases out there.

April 3, 2010 - (>= v2.2.1)
3 thanks

Careful with this method.

Despite the name and description, it will actually update any changed fields on the model rather than just the desired attribute.

def update_attribute(name, value)
  send(name.to_s + '=', value)

See? Use update_all and pass in the model ID as a condition, instead.