I have 3 models/tables: User, Task, and TaskInstance. The Task table is like a master list of tasks, not coupled to any particular user, whereas the TaskInstance table contains records that indicate a user’s completion of a particular task. In other words, a TaskInstance has a User id, a Task id, and a status boolean. A User has many TaskInstances. Users do not share TaskInstances, they each have their own collection.
What I would like to happen when a user first signs up for an account on the website is for the User.task_instances field to be populated with a new TaskInstance for every Task that exists in the master list.
From what I’ve read, I think I have to do this using before_create, because that should update the User before it gets saved for the first time. So far I have:
class User < ActiveRecord::Base
has_many :task_instances
before_create :populate_task_instances
private
def populate_task_instances
#something here
end
end
So far I’m unsure of what goes in the populate_task_instances method. How do I loop through every record in the Task table and create a TaskInstance for each, and then ensure that the collection of TaskInstances gets saved to the User’s task_instances field?
I understand this is pretty trivial but this is my first foray into Rails.
Here is one solution I think