views:

30

answers:

2

I'm trying to create default seed records for every user that signs up to the app. I'm thinking I could use the after_create method in my users observer model:

def after_create(user)
  user.recipes.create(:name => "Sample Recipe", :description => "This is a sample recipe.")
  user.cuisines.create(:name => "Sample Cusine", :description => "This is a sample cuisine.")
  ...
end

Is that too resource-intensive if I have 10 models that need seed data upon signup? Is there a more efficient way?

+4  A: 

You're doing this the correct way, and here's why:

  • As business logic (every user should start with a sample cuisine and recipe) it belongs in the model.
  • This is where it is most easily testable.
  • If they have to be created for each user anyway, there's no less "resource intensive" way to do it. Any kind of batch process would leave the user without these defaults for a time.

Personally, I'd probably skip the added abstraction and complexity of putting it in the observer, because I'd want it obvious upon reading through the model that this is happening. But that's personal preference, and there's nothing wrong with how you've set it up here.

Jaime Bellmyer
Thank you Jaime! I really appreciate your great answer. I'll place it in the models. Thank you :)
andy
Hey Andy - looking back, my first bullet might have been misleading. I was including observers when I said "the model". Observers are just as easy to unit test as models. And to be honest, your setup has me re-evaluating how I do my own. I think it makes a cleaner setup.
Jaime Bellmyer
A: 

Why not set those as the default values in your database? That way there's no extra resources being used code-wise, it is one less point of failure, and you don't need to manually build up the samples in the associations. You can give a default to a column like this:

class AddRecipesDefaults < ActiveRecord::Migration
  def self.up
    change_column :recipes, :name, :string, :default => "Sample Recipe"
    change_column :recipes, :default, :string, :default => "This is a sample."
  end

  def self.down
    change_column :recipes, :name, :string, :default => nil
    change_column :recipes, :name, :string, :default => nil
  end
end
Mike Trpcic
Setting the defaults doesn't auto-create new associations for a user, and that's the part that takes (minimal) extra cpu cycles.
Jaime Bellmyer