noizZze

Rails: Creating Associated Objects in AR

Assuming that you have an object Account like below

1
2
3
class Account < ActiveRecord::Base
  has_one :office
end

and you want to create an Office record when you create an account, you could do it in the after_create filter and it would be my way of doing that also. But the funny thing is that if you name the filter create_office, you don’t need to define the method itself. It will create the Office and link it to your Account model automagically. So here’s how the final class definition looks like:

1
2
3
4
class Account < ActiveRecord::Base
  has_one :office
  after_create :create_office
end

Amazing!