Notes posted to Ruby on Rails

RSS feed
September 7, 2011 - (v3.0.0 - v3.0.9)
0 thanks

Tested w/ Rails 3 and returning true/false ignored

Per http://ar.rubyonrails.org/classes/ActiveRecord/Callbacks.html “If a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled.” [and presumably associated action is not canceled]

So, the callback chain will be broken, but the save will still happen.

Also ran into this: http://innergytech.wordpress.com/2010/03/08/dont-put-validations-in-after_save/

September 7, 2011 - (>= v3.0.9)
0 thanks

Passing an object as argument

It is possible to pass an instance of a record to the method. See the documentation of polymorphic_url (http://apidock.com/rails/ActionDispatch/Routing/PolymorphicRoutes).

September 5, 2011
1 thank

(Another) Pluralize Without Showing the Count

Thought it would be best to take the source code from pluralize and just remove the count from the output.

Create this helper method in application_helper.rb

# Pluralize without showing the count.
def simple_pluralize count, singular, plural=nil
  ((count == 1 || count =~ /^1(\.0+)?$/) ? singular : (plural || singular.pluralize))

This allows you to pass in in the plural word to use as well.

August 30, 2011 - (>= v3.0.0)
1 thank

Does not work for has_one associations

If you are using this to validate that a has_one association has been made with another object this will not work, as the test used in the AssociatedValidator #validates_each method tests for nil and then ignores this object.

To test for association with a has_one association you can use the following code:

validate do
  [:teacher, :book].each do |attr|
    errors.add(attr, "is required") if self.send(attr).nil?
August 23, 2011
0 thanks

the correct return value of html_escape in example above

the correct return is:

# => is a > 0 & a < 10?

August 15, 2011
1 thank

The :path option

The path option will actually set the path and not the prefix I have found in Rails 3.0.5.


resources :my_reports, :path => 'my-reports'

All actions for this resource will now be at /my-reports.

August 14, 2011
0 thanks

Security issue

One thing to note about the code above is that it could have a security issue. If the user changes his/her password, the authentication token should expire. Hence, in a production scenario you should put in the password salt or something to allow the token to become invalidated.

August 11, 2011
2 thanks

More AREL compliant style is also possible

Code example

Person.where(:name => 'David').exists?
August 11, 2011 - (>= v3.0.0)
0 thanks

Look at mail gem

If you’re looking for mailer methods like “deliver” for rails 3 or later, you should look into “mail” gem: http://github.com/mikel/mail

August 9, 2011
1 thank

HTML5 support

To support multiple file selection simply pass :multiple => true in the options hash:

file_field_tag 'file', :accept => 'image/jpeg', :multiple => true
August 5, 2011
0 thanks

Speccing read_only requirements

To test if an attribute is defined readonly:

class MyModel < ActiveRecord::Base
  attr_readonly :important_type_thingie

describe MyModel do
 its('class.readonly_attributes') { should include "important_type_thingie" }

 it "should not update the thingie" do
   m = create :my_model, :important_type_thingie => 'foo'
   m.update_attributes :important_type_thingie => 'bar'
   m.reload.important_type_thingie.should eql 'foo'
August 4, 2011
1 thank

Examples out of order

The second and third examples should exchange places to fit with their explanations.

July 31, 2011 - (>= v3.0.9)
1 thank

Rescuing DeleteRestrictionError via flash message


class ShareType < ActiveRecord::Base
  has_many :shares, :dependent => :restrict


class ShareTypesController < ApplicationController
  def destroy
      flash[:success] = "successfully destroyed." 
    rescue ActiveRecord::DeleteRestrictionError => e
      @share_type.errors.add(:base, e)
      flash[:error] = "#{e}"
      redirect_to share_types_url
July 29, 2011 - (v2.1.0)
0 thanks

default value for :use_full_path

FYI, It in Rails 2.1.1 the default value for :use_full_path has changed from true to false.

This will show up as an error stating “No such file or directory”

July 29, 2011
0 thanks

Basic usage

Basic usage example:

class User < ActiveRecord::Base
   skip_callback :create, :after, :send_welcome_email
July 28, 2011 - (v3.0.0 - v3.0.9)
0 thanks

sure, but what types are there to chose from?

the ‘symbol’ parameter is not something specific like ‘:after_save’, but rather ‘:save’

I suppose ‘:update’ works as well.

July 27, 2011
1 thank

includes request parameters

fullpath includes request parameters in the result

July 27, 2011 - (>= v3.0.0)
0 thanks

Multiple update, on query ?

Person.update(people.keys, people.values)

Will this request issue one or multiple queries to update the table data (as in http://stackoverflow.com/questions/3432/multiple-updates-in-mysql#3466 )

The answer is: it will do TWO queries per updated row. One select and one update.

July 5, 2011 - (v3.0.0 - v3.0.9)
0 thanks

No way to use custom message

In what appears to be a bug, there appears to be no way to use a custom error message when using this validator.

July 2, 2011 - (<= v3.0.9)
0 thanks

Available Options and their meaning


Name of the cookie for the session


If true, session cookie is sent only to https hosts. This protects your app from session hijacking ( remember firesheep? )


Self explanatory (e.g. 60.minutes)


To which domain the cookie declares to be for

This very good post shows how to use :domain and :key to implement single-sign-on: http://itshouldbeuseful.wordpress.com/2011/02/02/rails-authlogic-and-single-sign-on/

July 1, 2011 - (>= v3.0.0)
0 thanks

Common Validator options

Most validators will support all of the following common options: (Through ActiveModel::Errors::CALLBACK_OPTIONS (http://apidock.com/rails/ActiveModel/Errors))

  • :if

  • :unless

  • :allow_blank

  • :allow_nil

July 1, 2011 - (<= v3.0.9)
0 thanks

Another way to use


link_to_unless_current("Profile", profile_path) 

%> also works (instead of pointing to controller/action)

June 29, 2011
2 thanks

Default values

For common attributes in several models, you can set a default human name like this:


    bez: Bezeichnung
    abk: Abkürzung
June 29, 2011
0 thanks

Updating nested attributes of one-to-one associations

As the documentation implicitly mentions, when updating nested attributes of a one-to-one relationship, you need to pass the ID of the nested attribute itself, otherwise a new record will be created.

This works fine:

params = { :member => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }

However, the following line will build and save a new record, which is usually not what you want for one-to-one:

params = { :member => { :avatar_attributes => { :icon => 'sad' } } }

Alternatively, you can use the ‘update_only’ option. This option will ensure that an existing record will always be updated, even if the ID is not specified:

accepts_nested_attributes_for :avatar, :update_only => true
June 28, 2011 - (v3.0.9)
0 thanks

available column types

Rails 3.0.9 update for RobinWu’s post

Available column types:

:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean


MyClass < ActiveRecord::Migration

def change
  create_table :myclass do |t|
    t.string :name
    t.text :content


June 28, 2011
0 thanks

Typo in example above

You aren’t mistaken. That is an error in the example with the block above. There’s an extra ‘(’ character.

June 24, 2011 - (v3.0.0 - v3.0.9)
1 thank

RailsCast about Responders

See Ryan Bate’s excellent RailsCast #224 about Responders in Rails 3.x: http://asciicasts.com/episodes/224-controllers-in-rails-3

June 23, 2011
0 thanks

RE: Don't Use to_formatted_s(:db) on an Array of IDs

The reason it doesnt work @joshuapinter for IDs is because if you look at the source:

case format
  when :db
    if respond_to?(:empty?) && self.empty?
      collect { |element| element.id }.join(",") # look at this line

It maps/collects the object ids and then joins them using a comma ; so in the case of 60 for instance :

60.object_id #=> 121

60.id #=> 121

June 22, 2011
1 thank

:url conflicts with :format

If you are passing both :url and :format, url overwrites the use of format, so you’ll need to pass it in the url like so:

form_for user, :url => user_path(@user, :format => :json)