Ruby on rails 在创建父记录后自动创建关联记录

Ruby on rails 在创建父记录后自动创建关联记录,ruby-on-rails,activerecord,model,after-create,Ruby On Rails,Activerecord,Model,After Create,我正在构建一个项目应用程序,我需要在创建项目记录时自动生成1名参与者 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: curren

我正在构建一个项目应用程序,我需要在创建项目记录时自动生成1名参与者

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
我的模型
类项目
当我尝试此操作时,会出现以下错误:

undefined method `participant' for #<Project:0x007fb402707250>
未定义的方法“参与者”#

您的代码中有一个输入错误

以下是:

self.participant.create
应该是:

self.participants.create
因为模型
有多个:参与者
,而不是
有一个:参与者

我还看到您在模型中使用了
当前用户
@role
。如果您希望它们被控制器转发,那么这种情况就不会发生。该助手和变量在模型中不可访问,即使在修复上述输入错误后,也会使方法崩溃


如果您的项目以某种方式存储了用户和角色,我建议您从
self
对象中获取,以创建您的参与者。

啊,谢谢。我的项目将当前用户存储为用户id。。。要访问这些,我需要编写self.participants.create!(用户id::用户id级别:1,参与者类别::角色,添加者::用户id)?
self.participants.create!(user\u id:self.user\u id,级别:1,参与者\u cat:self.role,添加者:self.user\u id)
如果我的回答回答了您的问题,请将其标记为我的回答。