寻找一个好主意和一个好的 Ruby 结构 [英] Looking for a good idea and a good Ruby structure

查看:48
本文介绍了寻找一个好主意和一个好的 Ruby 结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Rake 任务来填充数据库以用于开发目的,以便处理一些数据.(但在测试中我使用的是 FactoryGirl,所以不讨论这个.)

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.

现在问题开始了:我有更多的表格要填充!例如Summaries表挂在Organization表上,所以每个组织可以有很多Summaries,所以我们在Summary表中也有一个organization_id外键来填充.但是我仍然想要一个像 create_summaries 这样的方法,它的作用类似于上面的 create_organization 方法,但是这次填充的是总结表,而棘手的部分是填充它表的 organization_id 字段.

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.

我应该如何解决这个问题?假设总结表有这些字段: id (auto generate by Rails) , organization_id, name, member_count

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

推荐答案

尝试将 Populator gem 用于此类任务.它易于使用,您可以生成复杂的结构.截屏.

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

这篇关于寻找一个好主意和一个好的 Ruby 结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆