Read more

Always, always declare your associations with symbols

Tobias Kraze
September 25, 2012Software engineer at makandra GmbH

This is not relevant for Rails 5.2+.

Never ever declare your associations with a string, especially when doing metaprogramming. A common mistake is something like

# WRONG
class Page < ActiveRecord::Base
  %w[main sub].each do |type|
    belongs_to "#{type}_title"
  end
end

   
# RIGHT
class Page < ActiveRecord::Base
  %w[main sub].each do |type|
    belongs_to :"#{type}_title"
  end
end
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

Always convert to a symbol, otherwise you'll have all kinds of fun.


Newer rails / activerecord (at least 5.2) will throw an association names must be a Symbol (ArgumentError) error if you define an association as string.

Posted by Tobias Kraze to makandra dev (2012-09-25 14:41)