Coda Chang Coda Chang - 17 days ago 6
Ruby Question

Refactor rails controller code

I was tring to reduce duplicatie code in my Rails project.

def update_receipt
user = current_user
Receipt.update(user.receipt.id, name: params[:name].to_s, phone_number: params[:phone_number].to_s, address: params[:address].to_s, receipt_type: params[:receipt_type].to_i)
Receipt.update(user.receipt.id, name: params[:name].to_s, phone_number: params[:phone_number].to_s, address: params[:address].to_s, receipt_type: params[:receipt_type].to_i, tax_number: params[:tax_number].to_i) if params[:receipt_type].to_i == 2
end


Is there a better way to refactor the above codes?

Answer

Updated answer:

def update_receipt
  attrs = params.slice(:phone_number, :address, :receipt_type)
  attrs[:tax_number] = params[:tax_number] if attrs[:receipt_type].to_i == 2
  Receipt.update(user.receipt.id, attrs)
end