Rails Gotchas
From eyeRwiki
A log of all the stupid mistakes I make while learning rails. Maybe someone will find them useful.
[edit] ActiveRecord initialize
DO NOT Override the initialize method of ActiveRecord. It only causes problems!
[edit] Serializing an array of custom classes =
class Board < ActiveRecord::Base
# The next line is necessary if you want @pegs to unserialize
# in the expected manner. If you don't have it, YAML won't know
# what class the items in the array should be.
require 'board_peg'
serialize :pegs
def setup_board
self.pegs = [BoardPeg.new, BoardPeg.new, BoardPeg.new]
end
end
class BoardPeg
...
end
[edit] Associations w/o default names
If you decide to override the default name of a has_one/has_many and belongs_to relationship, you CAN NOT just do this:
class Person < ActiveRecord::Base has_one :car, :class_name => "Vehicle" class Vehicle < ActiveRecord::Base belongs_to :driver, :class => "Person"
You MUST include foreign keys like so:
class Person < ActiveRecord::Base has_one :car, :class_name => "Vehicle", :foreign_key => "person_id" class Vehicle < ActiveRecord::Base belongs_to :driver, :class => "Person", :foreign_key => "person_id"
