DEV Community

Vincent Bakker
Vincent Bakker

Posted on

Clone record with overrides

The clone_with_overrides function duplicates the original record using the dup method, assigns the overridden fields from the overrides hash, saves the new record, and returns it.

class Person < ApplicationRecord
  def clone_with_overrides(overrides = {})
    # Create a new instance of the model
    new_record = self.dup

    # Assign the overridden fields to the new instance
    overrides.each do |field, value|
      new_record[field] = value
    end

    # Save the new record
    new_record.save

    # Return the cloned record with overrides
    new_record
  end
end
Enter fullscreen mode Exit fullscreen mode

To use this function, you can call it on an instance of the model and pass a hash of field-value pairs to override. Here's an example usage:

# Assuming you have an existing record with ID 1
original_record = Person.find(1)

# Clone the record and override some fields
cloned_record = original_record.clone_with_overrides(
  name: 'John',
  age: 42
)

# The cloned record is saved and ready to use
puts cloned_record.inspect

Enter fullscreen mode Exit fullscreen mode

Make sure to adjust the field names and their types according to your model's attributes.

Top comments (0)