Recent notes

RSS feed
August 17, 2009
1 thank

Time in fixtures

When creating fixtures you should use this method to set created_at/updated_at timestamps correctly:


This won’t work as expected (created_at/updated_at will be nil) a

  episode: active1
  play_id: 1
  play_time: 20
  country: United Kingdom
  created_at: <%= Time.parse('22:00 14 Aug 2009') %>
  updated_at: <%= Time.parse('22:00 14 Aug 2009') %>

but this will work as expected:

  episode: active1
  play_id: 1
  play_time: 20
  country: United Kingdom
  created_at: <%= Time.parse('22:00 14 Aug 2009').to_s(:db) %>
  updated_at: <%= Time.parse('22:00 14 Aug 2009').to_s(:db) %>
August 16, 2009
1 thank

Small notice about recognize urls with specific HTTP verbs

This is wrong ruby syntax:

assert_recognizes {:controller => 'items', :action => 'create'}, {:path => 'items', :method => :post}

Parentheses are obligatory in this case:

assert_recognizes({:controller => 'items', :action => 'create'}, {:path => 'items', :method => :post})
August 15, 2009
0 thanks

To find element ant not to find element

If you want to see administration panel:

assert_select "div.admin-panel"

But if you want to NOT see administration panel just write:

assert_no_tag 'div', :attributes => {:class => 'admin-panel'}
August 13, 2009
3 thanks

With multiple parameters


   :url => some_remote_function_path, 
   :with => "'key1='+$('elem_id').value +'&key2='+$('elem_id').value+ '&this_elem_value='+value"
August 13, 2009
0 thanks

no overwrite

const_set does not overwrite, it only create new ones

August 13, 2009 - (>= v2.3.2)
3 thanks

with_exclusive_scope example by Ramon broken in latest Rails

The example Ramon gave works within the model itself, i.e.

class Article
  def closed
    with_exclusive_scope { find(:all) }

However, from what I can see, this approach does not work within a controller. You may be wanting to use

Article.with_exclusive_scope { find(:all) }  #=> "SELECT * FROM 'articles'

But it will error out about find(:all) not existing on ArticlesController. To get around this, you must now do

Article.with_exclusive_scope { Article.find(:all) }  #=> "SELECT * FROM 'articles'

In otherwards, find(:all) isn’t being executed in the scope of the model, but in the controller in which its called.

Took me a minute or two to find out, so I thought I’d let others know.

August 12, 2009
0 thanks

Current Database Name: Sqlite version

Get the current database name when using Sqlite:

August 11, 2009
2 thanks

Common signals

Some of the more commonly used signals:

1       HUP (hang up)
2       INT (interrupt)
3       QUIT (quit)
6       ABRT (abort)
9       KILL (non-catchable, non-ignorable kill)
14      ALRM (alarm clock)
15      TERM (software termination signal)
August 10, 2009
0 thanks

Content type for emails with attachments

Be aware that if you want to send emails with attachments, you probably want to use the content type multipart/mixed for the overall email.

The MIME time multipart/alternative is intended for emails where each part is a different representation of the same message.

After following the 2.3.2 documentation we used multipart/alternative to attach files to our mails, however this then caused Hotmail to ignore the attachments. It turns out it thought they were all alternative versions of the HTML content (which it could already display, so the alternatives weren’t necessary)

August 8, 2009
2 thanks

Re: Validate an optional URL field

Actually it’s easier to use validates_format_of for this task. Please refer to the comments under the doc.

August 7, 2009
7 thanks

Join multiple tables

It’s easy to join multiple tables too. In this case we have:

class Article
  belongs_to :feed

class Feed
  has_many :articles
  belongs_to :source

class Source
  has_many :feeds
  # t.bool :visible

You can search articles and specify a condition on the sources table.

  :conditions => { :feeds => { :sources => { :visible => true }}}, 
  :joins => [:feed => :source],
August 7, 2009
0 thanks
August 7, 2009
0 thanks

Most common use case

Most common use case is probably:

Rails.cache.fetch "some key" do
  compute some value

This computes some value and caches it. Subsequent invocations will return cached value (as long as it is still cached).

August 7, 2009
2 thanks


This method only returns a cache manager object of sorts, to see what you can do with it, see ActiveSupport::Cache::Store.

August 6, 2009
4 thanks

Documentation bug

When adding the :target option, the documentation states that you should user :href_options like so:

auto_link(post_body, :href_options => { :target => '_blank' })

However, I could only get it to work using :html instead:

auto_link(post_body, :html => { :target => '_blank' })

I’m using Rails 2.2.2, but I believe that this also happens for more recent version .

August 6, 2009
2 thanks

Second example is correct

@taryneast, the second example is correct. The receiver’s #size limits the result’s.


August 6, 2009
1 thank

*Described above

The documentation is referring to the module documentation: ActionController::Cookies

August 4, 2009 - (>= v2.2.1)
1 thank

Binding parameter deprecated in > 2.2

Supplying the binding argument produces a deprecation warning in 2.2 and newer:

DEPRECATION WARNING: The binding argument of #concat is no longer needed. Please remove it from your views and helpers.

August 3, 2009 - (v1_8_6_287)
0 thanks

Using YAML

YAML library must be required.

Example to display an array as yaml formatted output

require 'yaml'

puts [100, [99, 98, 97], 96, 95].to_yaml
August 3, 2009
0 thanks

Separating date and time

Option :datetime_separator can be set too. Default is ‘ &mdash; ’

July 31, 2009 - (v1_8_7_72)
1 thank



July 31, 2009 - (v1_8_7_72)
0 thanks


Synonym for File.exist?

July 30, 2009
2 thanks

How to set default value to NULL

To set default value to NULL you can use change_column method instead, for example:

change_column :suppliers, :qualification, :string, :default => nil

Just make sure you don’t change data type accidentally ;-)

July 30, 2009 - (>= v2.3.2)
0 thanks

can we use both sortable_element and drop_recieving_element on same list

I had a sortable_element that was also a drop_receiving_element. element it’s dropping while dropping element into selected container ,but not element dragging is not viewble to end users. it’s dragging only in sortable list area. but mu droppble contanier is another one.i used scroll => true in sortable_element . but its not working for sorting and dropping element into contianer. could u letme know how to use both methods on same list

July 29, 2009
0 thanks

Paginating grouped records

If you are grouping similar records and paginating you might need to use :group You’ll want to :select only the field you’re collapsing on probably.

Model.count(:select => :attribute, :group => :attribute)

This will return an OrderedHash of your attributes with a count for each.

{"Column Content" => 6, "Another Column's Content" => 8}

You’ll need a second query to pull all of your records out.

July 28, 2009
8 thanks

Return True

As is the case with the before_validation and before_save callbacks, returning false will break the callback chain. For example, the expire_cache_id method will not run if Rails.cache.expire returns false (as it will if the key is not cached with memcache).

Returning False Example (Bad)

after_save :expire_cache_by_name
after_save :expire_cache_by_id

def expire_cache_by_name

def expire_cache_by_id

Returning True Example (Good)

def expire_cache_by_name
  return true

def expire_cache_by_id
  return true
July 27, 2009
0 thanks

Include the 'abbrev' module

To get this access to this method you must:

require 'abbrev'
July 27, 2009 - (>= v2.2.1)
3 thanks

Overriding default validation messages

Before Rails 2.2 you could globally customize the default validation error messages by changing AR::Base.default_error_messages. The messages have now been moved to i18n, so to customize them in 2.2 and up, just create a locales/ folder in your config/ folder, copy activerecord/lib/active_record/locale/en.yml (in Rails source) to config/locales/en.yml, and then change the strings inside. As szeryf indicated below, the strings of interest are activerecord.errors.messages.

July 24, 2009
1 thank

Instance method

Please note that this is an instance method, not a class method (which seemed more logical for me and took me a while to see what’s wrong). So, you call it like this:

User.new.from_json '{"id": 1, "name": "DHH"}' # RIGHT!

not like this:

User.from_json '{"id": 1, "name": "DHH"}' # WRONG!
July 23, 2009 - (v1.0.0 - v2.3.2)
0 thanks

Format meaning:

%a - The abbreviated weekday name (“Sun”)

%A - The full weekday name (“Sunday”)

%b - The abbreviated month name (“Jan”)

%B - The full month name (“January”)

%c - The preferred local date and time representation

%d - Day of the month (01..31)

%H - Hour of the day, 24-hour clock (00..23)

%I - Hour of the day, 12-hour clock (01..12)

%j - Day of the year (001..366)

%m - Month of the year (01..12)

%M - Minute of the hour (00..59)

%p - Meridian indicator (“AM” or “PM”)

%S - Second of the minute (00..60)

%U - Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)

%W - Week number of the current year, starting with the first Monday as the firstday of the first week (00..53)

%w - Day of the week (Sunday is 0, 0..6)

%x - Preferred representation for the date alone, no time

%X - Preferred representation for the time alone, no date

%y - Year without a century (00..99)

%Y - Year with century

%Z - Time zone name

%% - Literal “%” character