automatically create an associated record after creation of a parent record

573 views Asked by At

I am building a Project app and I need to automatically generate 1 Participant on creation of a Project record.

My model

class Project < ActiveRecord::Base
has_many :participants, dependent: :destroy, inverse_of: :project

after_create :build_a_role

private
  def build_a_role
     self.participant.create!(user_id: current_user.id, level: 1, participant_cat: @role.id, added_by: current_user.id)
  end

end

When I try this I get this error:

undefined method `participant' for #<Project:0x007fb402707250>
1

There are 1 answers

2
SHS On BEST ANSWER

You have a typo in your code.

The following:

self.participant.create

should be:

self.participants.create

Because the model has_many :participants, not has_one :participant

I also see that you're using current_user and @role in your model. If you're expecting them to be forwarded them by the controller, then this won't happen. That helper and variable will not be accessible in the model and will make your method crash even after you fix the above-mentioned typo.

If your Project stores the user and role somehow, I suggest you take from the self object for the creation of your participant.