Reputation: 15374
How to set up my seed file to create my data with associated records?
So far I have:
# 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) }
The relationship being:
component has_many :strands
strand belongs_to :component
Within this I want to assign component_array[0]
to the first 3 elements in my array and component_array[1]
to the remaining 4 elements.
What syntax should I use, would I be looking at a hash here?
Upvotes: 0
Views: 71
Reputation: 8331
It's rather easy to assign models to their relationships.
In your case, the 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
Likewise, to assign a has_many relationship
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
Upvotes: 1