user1899082
user1899082

Reputation:

Looking for a good idea and a good Ruby structure

I am writing a Rake task to populate a database for development purposes to have some data to work with. ( but In test I am using FactoryGirl, so not talking about that. )

So let's say I have two sample Organizations in my demo database, so I have defined them like this:

sample_organizations = [ '37 Signals', 'Fog Creek']

and then a small method to populate the DB like this:

def create_organizations
  sample_organization.each { |item|
    Organization.first_or_create(
        name: item,
        time_zone: 'Central'
    )
  }
end

so the good thing is that two months from now if I wanted to add a third organization I just go to top of my code and hand type another organization name in that array. Method still works and creates it.

Now here starts the question: I have more tables to populate! For example Summaries table which is hanging off of Organization table, so each organization can have many Summaries, so we have an organization_id foreign key in Summary table to fill too. But still I want to have a method like create_summaries that does something similar to create_organization method above, but this time fills in Summaries table, and the tricky part is to fill in that organization_id field of the table.

How should I approach this? Let's say Summaries table has these fields: id (auto generate by Rails) , organization_id, name, member_count

Upvotes: 1

Views: 64

Answers (1)

Matzi
Matzi

Reputation: 13925

Try using Populator gem for tasks like this. It is easy to use, and you can generate complex structures. Screencast.

As you can't use those, use select a random parent object, or specify one by name in a hash.

summaries = [{:name => "foo", :organization => "bar"}]

Upvotes: 1

Related Questions