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?
2 Answers 2
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.
-
\$\begingroup\$ Welcome to Code Review! Could you explain why this code is better ? Why use after_save instead of after_create ? We don't just post code here, we want to help the Op by explaining things! \$\endgroup\$Marc-Andre– Marc-Andre2016年05月03日 13:11:36 +00:00Commented May 3, 2016 at 13:11
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
"Foo"
and"Bar"
? We don't like it when foo/bar appear in Code Review questions, because it's a sure sign that you're hiding some information from us. \$\endgroup\$