Reputation: 11460
I would like to populate various tables in my database after a new customer signs up to use our web application. I'm wondering what the best way to do this is, the main requirement being that it should not require any intervention by me. Most of the data is static (but can be changed by the customer later (like preferences for example)), but will obviously need the customer's ID as a way of linking the created records to this customer.
I considered putting a few
Object.create(:customer_id => @customer.id, :yummy => "maybe", :etc => true)
statements in the controller that handles signups, but that annoying little alarm bell that tells me there's a better way is going off again!
Thanks in advance for any suggestions!
Gav
Upvotes: 2
Views: 298
Reputation: 5248
I'm using a YAML file to populate more than ten tables in database during signup. This approach has some positive side-effects for me:
There have been some downsides too:
As i get around 300 new signups in a day, it's too early for me to worry about performance.
Upvotes: 0
Reputation: 146
@Omar Qureshi You shouldn't use trigger function in your database - there are many features that can be done by them, but ActiveRecord is database-agnostic and it has callbacks that handle such things that triggers can. Using something that links you to a specific DB system is wrong.
@dmathieu's answer seems to be the best. And you should consider using Factory girl - it's a great tool for populating the DB.
Upvotes: -1
Reputation: 32627
The problem with khelll's solution is that if you create a new Account using from outside of the register action (for example, in an admin module), it's database won't be populated.
So I'd prefer something like the following :
class Account < ActiveModel::Base
def after_create
populate
end
private
def populate
# Your logic
end
end
The after_create callback will be called after any account creation.
That's more MVC and DRY compliant ;)
Upvotes: 3
Reputation: 24010
In your controller
class AccountController < ApplicationController
after_filter :populate_db :only=>[:register]
def populate_db
# whatever stuff
Account.populate
end
end
And put the logic inside your model:
class Account < ActiveModel::Base
def populate
# your logic
end
end
Upvotes: 2
Reputation: 9093
two ways
Upvotes: 0