Reputation: 1150
I am trying to seed some data into my database and I have a couple of questions regarding rails relationships.
I am trying to improve my understanding based on http://guides.rubyonrails.org/association_basics.html
a. With the has_many and belongs_to relationship. Can it be done with existing models?
Take for example I have 2 models subjects and lessons both already created. To model the relationship, do I just add the subject_id to lessons? Or are there any additional data I would need to include for such a relationship.
I have looked around and with the following example they created the nested model together with the existing model. They seeded the nested model within contact_attributes for example. How to db:seed a model and all its nested models?
But I am not too sure how to work around it if the child model was already previously created and is it enough to show such a relationship with add the id of the parent model while I am seeding data.
b. has_and_belongs_to_many
With the has_many_and_belongs_to relationship, from the rails guide, there is an additional table. For eg. subjects and lessons. I would have to generate an additional table subjects_lessons. Similarly if I were to create such an relationship is seeding data into that table sufficient or are there additional steps to it?
Would appreciate it if someone could help me answer my doubts.
Upvotes: 1
Views: 226
Reputation: 9426
Your initial thought is correct. Assigning the subject_id
is sufficient given a relationship like the following:
Relationships:
class Subject < ActiveRecord::Base
has_many :lessons
end
class Lesson < ActiveRecord::Base
belongs_to :subject
end
seed_data.rb example:
class SeedData
def self.run!
@subject = Subject.create()
@lesson = @subject.lessons.create
# @lesson.subject == @subject
# @subject.lessons == [@lesson]
end
end
Rake file:
require "seed_data"
desc "Seed database"
task :seed_data do
SeedData.run!
end
CLI:
rake seed_data
Upvotes: 2
Reputation: 798
Just create your parent items first in the seed file then assign the ids of the parent items to the child items... The parent items just need to exist first before you can create the children items. Seeding data will work and should be sufficient depending on your need.
Upvotes: 0