I have a database in my Rails app that holds a list of positions in each project. The user can add/delete positions for the current project they are working on. There are a few of these positions I would like to come as defaults when a user creates a new project. Is this possible?
2 Answers
Yes. I'd suggest using an after_save callback in your project model
So, in your model:
def before_save
@was_a_new_record = new_record?
return true
end
after_save :create_positions
def create_positions
Position.create name: 'Manager', project_id: self.id if @was_a_new_record
# repeat as required
end
3 Comments
Tim
OK, I seem to get in trouble for making too many assumptions, as I fill in some gaps with likely values, and assume that these will be adjusted to match how models are actually set up. My bad, I'll go more carefully. I have assumed your Position class name and the variables you've assigned in it. Do they match, do you have a particular error?
Dan Brookwell
I have a position title string called
positions and each position has a project_id which should be the new project created. I have adjusted the code you provided to fit these values and I don't get an error however nothing seems to show up on the table I have that should show the positions associated with the current project. EDIT: i just debugged a bit and see there is no project_id being saved on the create.Tim
Ah, stupid me, I'd is not set yet. I'll do a quick amend
#app/models/project.rb
class Project < ActiveRecord::Base
has_many :positions
before_create :set_positions
accepts_nested_attributes_for :positions #-> required for Rails 4.2+
private
def set_positions
3.times do
self.positions.build
end
end
end
when a user creates a new project
The above will build the associated position objects before you create a project. You can add specific attributes to each of the new objects:
self.projects.build name: "test"
The beauty of it is that all the records will be saved at the same time, making it especially efficient.
1 Comment
Dan Brookwell
Each position has an associated project_id, would that be able to be created through this method as well? If you look at the answer above yours that would show this dilemma.