Rails create create default database records

Posted on

Problem

In my application I have an accounts model:

class Account < ActiveRecord::Base
  belongs_to :user
  has_many :invoices
end

The Account model belongs to the User model. After the user is created, some default accounts must be created:

class User < ActiveRecord::Base
  has_many :accounts

  after_create do
    Account.create(name: "Repairs",user: self)
    Account.create(name: "Supplies", user: self)
  end
end

Invoices can then be assigned to one of these initial accounts:

class Invoice < ActiveRecord::Base
  belongs_to :accounts
end

Is this the proper way to to create the default accounts?

Solution

Yeah! you are on right path but we can improve it like :

class User < ActiveRecord::Base
  has_many :accounts

  after_save do
    self.accounts.create([{name: "Repairs"}, {name: "Supplies"}])
  end
end

Hopefully! This will help.

Instead of an after_save callback, which only creates those records after saving the object, why not after_initialize (Reference):

class User < ActiveRecord::Base
  has_many :accounts

  after_initialize do
    unless persisted?
      accounts << Account.new(name: 'Repairs', user: self)
      accounts << Account.new(name: 'Supplies', user: self)
    end
  end
end

Now the moment you have a new User object, you have default accounts (though unpersisted):

@user = User.new

puts @user.accounts[0].name # echoes "Repairs"
puts @user.accounts[1].name # echoes "Supplies"

The new accounts will be saved upon saving the user object:

@user.save

Leave a Reply

Your email address will not be published. Required fields are marked *