Looking for a good idea and a good Ruby structure

寵の児 提交于 2019-12-11 04:41:50

问题


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


回答1:


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"}]


来源:https://stackoverflow.com/questions/14911323/looking-for-a-good-idea-and-a-good-ruby-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!