1
\$\begingroup\$

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?

\$\endgroup\$
4
  • \$\begingroup\$ Explain what you mean by "default accounts"? \$\endgroup\$ Commented Apr 30, 2016 at 21:10
  • \$\begingroup\$ I updated question. \$\endgroup\$
    – James
    Commented Apr 30, 2016 at 21:15
  • 1
    \$\begingroup\$ It seems like an unusual thing to do, and it's still not very clear why you want to do this. And what do you really mean by "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\$ Commented Apr 30, 2016 at 21:17
  • \$\begingroup\$ I attempted to provide more information. Do you find this useful? \$\endgroup\$
    – James
    Commented Apr 30, 2016 at 21:31

2 Answers 2

1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\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
    Commented May 3, 2016 at 13:11
1
\$\begingroup\$

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
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.