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>
You have a typo in your code.
The following:
should be:
Because the model
has_many :participants
, nothas_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.