nifCody
nifCody

Reputation: 2444

Generating a code failed on afterr_save call back on rails

I am trying to adding a unique value in a table column when the record is saved.

Assume my table have 3 fields : < Job_Code >

In my POST request I send the following payload :
{ "customer_id":"123", "customer_name":"Jay"}

If this record is saved to the database. Then I need to update the Job_Code column in using generated code like JOB_123_458 where 458 is the unique id for the record.

I am tying to using the after_save callback on Active Class and update the new value on it.

I am using the following way :

after_save :update_job_code

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

But I could not able to generate a Job code in the format of JOB_<Customer_id>_<Newly Created Job Id>

Let me know how do i generate the job code in relevant format in Active Record after_save call back

Upvotes: 0

Views: 33

Answers (2)

Mikhail Nikalyukin
Mikhail Nikalyukin

Reputation: 11967

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

Just remove : it's for symbols definitions, you want to actually call attributes.

Upvotes: 1

jvnill
jvnill

Reputation: 29599

:customer_id and :id are just symbols. What you want is to call the attributes of the record so just remove the colons.

It is also better to use string interpolation so instead of creating multiple strings, you just create a single string.

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

Upvotes: 1

Related Questions