I am using the cocoon gem for nested records and because the form will be submitted by ajax and must remain in the form after submitting the data for creation, I need to modify the create method of the nested records model because every time the form is saved the same records are created despite having been created previously when the user previously saves the form.
Is it possible to overwrite the create method of the model so that at the time of saving the records it first looks for if the record exists and if it does it updates the record?
I had done something like this:
class PayrollEmployee < ApplicationRecord
belongs_to :payroll
belongs_to :employee_contract
def create_or_update
payroll_employee = PayrollEmployee.find_by_payroll_id_and_employee_contract_id(payroll_id, employee_contract_id) || PayrollEmployee.new()
payroll_employee.update_attributes!(:payroll_id => payroll_id, :employee_contract_id => employee_contract_id) #etc etc
end
end
but I get this error:
ArgumentError (wrong number of arguments (given 1, expected 0)):
app/models/payroll_employee.rb:6:in `create_or_update'
app/controllers/payrolls_controller.rb:122:in `block in update'
app/controllers/payrolls_controller.rb:121:in `update'
your
create_or_updatemethod atPayrollEmployeemodel is not accepting any arguments, I guess at payroll controller you have passed an argument. that's why it gives thisArgumentError (wrong number of arguments (given 1, expected 0)):errorso you should add an argument at your defined
create_or_updatemethod, or you should remove the passed value from the method in controller.