【问题标题】:automatically create an associated record after creation of a parent record创建父记录后自动创建关联记录
【发布时间】:2014-12-23 15:46:25
【问题描述】:

我正在构建一个项目应用程序,我需要在创建项目记录时自动生成 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>

【问题讨论】:

    标签: ruby-on-rails activerecord model after-create


    【解决方案1】:

    您的代码中有错字。

    以下内容:

    self.participant.create
    

    应该是:

    self.participants.create
    

    因为模型has_many :participants,而不是has_one :participant

    我还看到您在模型中使用了current_user@role。如果您希望它们由控制器转发它们,那么这不会发生。该帮助器和变量将无法在模型中访问,即使您修复了上述拼写错误,也会使您的方法崩溃。

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

    【讨论】:

    • 啊,谢谢。我的项目确实将 current_user 存储为 user_id... 来访问这些,我会写 self.participants.create!(user_id: :user_id level: 1,participant_cat: :role, added_by: :user_id) 吗?
    • self.participants.create!(user_id: self.user_id, level: 1, participant_cat: self.role, added_by: self.user_id) 如果我的回复回答了您的问题,请将其标记为回复。
    猜你喜欢
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    相关资源
    最近更新 更多