afterr_save 回调生成代码失败 rails

Generating a code failed on afterr_save call back on rails

我试图在保存记录时在 table 列中添加一个唯一值。

假设我的 table 有 3 个字段:< Job_Code >

在我的 POST 请求中,我发送了以下负载:
{ "customer_id":"123", "customer_name":"Jay"}

如果这条记录保存到数据库中。然后我需要使用生成的代码更新 Job_Code 列,例如 JOB_123_458,其中 458 是记录的唯一 ID。

我打算在 Active Class 上使用 after_save 回调并更新其上的新值。

我正在使用以下方式:

after_save :update_job_code

def update_job_code
   update_column(:job_code, "JOB_" + :customer_id + "_" + :id)
end

但是我无法生成 JOB_<Customer_id>_<Newly Created Job Id>

格式的工作代码

请告诉我如何在 Active Record 中生成相关格式的作业代码 after_save 回调

after_save :update_job_code

def update_job_code
   p customer_id.inpsect # to see customer id in log for debug
   update_column(:job_code, "JOB_" + customer_id + "_" + id) unless job_code.present?
end

只需删除 : 它用于符号定义,您想要实际调用属性。

:customer_id:id 只是符号。你想要的是调用记录的属性,所以只需删除冒号。

使用 string interpolation 也更好,这样您无需创建多个字符串,只需创建一个字符串即可。

def update_job_code
  update_column(:job_code, "JOB_#{customer_id}_#{id}")
end