Home > database >  how to update/create has_one associated data efficiently in rails
how to update/create has_one associated data efficiently in rails

Time:11-25

Hi i am learning rails and i got the situation where i have to update or create the data for has_one associated model/table.

I tried this

Worker.rb

class Worker < ApplicationRecord
  has_one :worker_encrypted_info
end

worker_encrypted_info.rb

class WorkerEncryptedInfo < ApplicationRecord
  belongs_to :worker
end

workers_controller.rb

def update_personal_info
   if @worker.update(update_personal_info_params)
     @worker.create_worker_encrypted_info(sin: params[:worker_encrypted_info][:sin])
   end
end

now what

@worker.create_worker_encrypted_info(sin: params[:worker_encrypted_info][:sin])

is doing is first updating worker_encrypted_info record with worker_id: nil and then creating new record for same worker_id instead of updating the old one. which is not very great ofcourse because i dont need that worker_id: nil record in my database at all. why do i need to delete that previous one manually with .destroy code? is there any Efficient way to do so?

CodePudding user response:

I would expect that this works

def update_personal_info
  return unless @worker.update(update_personal_info_params)

  if @worker.worker_encrypted_info  
    @worker.worker_encrypted_info.update(sin: params[:worker_encrypted_info][:sin])
  else
    @worker.create_worker_encrypted_info(sin: params[:worker_encrypted_info][:sin])
  end
end

CodePudding user response:

i acheived it with active record nested attributes

  • Related