创建组合两个模型的种子文件

时间:2014-11-28 08:30:03

标签: ruby-on-rails ruby arrays seed

如何设置种子文件以创建包含相关记录的数据?

到目前为止,我有:

# Arrays
strand = ['Oracy across the curriculum', 'Reading across the curriculum', 'Writing across the curriculum', 'Developing numerical reasoning', 'Using number skills', 'using measuring skills', 'Using data skills']
component_array = Component.all.map(&:id)

# Add each item in array
strand.each { |sample| Strand.create(name: sample) }

关系是:

component has_many :strands
strand belongs_to :component

在此范围内,我想将component_array[0]分配给数组中的前3个元素,将component_array[1]分配给其余4个元素。

我应该使用什么语法,我会在这里查看哈希吗?

1 个答案:

答案 0 :(得分:1)

将模型分配给他们的关系相当容易。

在您的情况下,Strand belongs_to Component

name_arr = ['Oracy across the curriculum', 'Reading across the curriculum', 'Writing across the curriculum', 'Developing numerical reasoning', 'Using number skills', 'using measuring skills', 'Using data skills']
components = Component.all

name_arr.each_with_index do |name, index|
  strand = Strand.new(:name => name)

  # associate a component to your strand
  # this will add the component_id of your strand
  strand.component = components.first if index < 3
  strand.component = components[1] if index >= 3

  strand.save
end

同样,指定 has_many 关系

component = Component.new(:foo => :bar)
strand = Strand.new(:name => 'Oracy across the curriculum')

# assign it to the strand, automatically adds fitting id
component.strands << strand
component.save