Создание начального файла, объединяющего две модели

Как настроить мой начальный файл для создания моих данных со связанными записями?

Пока у меня есть:

# 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 элементам.

Какой синтаксис мне следует использовать, буду ли я смотреть здесь на хэш?


person Richlewis    schedule 28.11.2014    source источник
comment
какая связь между Component и Strand? Это Strand belongs_to :component и Component has_many :strands?   -  person davegson    schedule 28.11.2014
comment
извините, забыл добавить отношения, просто добавил их в вопрос   -  person Richlewis    schedule 28.11.2014


Ответы (1)


Довольно легко назначать модели их отношениям.

В вашем случае Strand принадлежит_к 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
person davegson    schedule 28.11.2014
comment
спасибо за вашу помощь, но по какой-то причине это не создает и не индексирует значение - person Richlewis; 28.11.2014
comment
индекс возвращает нулевые значения - person Richlewis; 28.11.2014