handle unknown attributes in activeRecord

·

2 min read

When using ActiveRecord::new to create a new record in Rails, you may encounter the ActiveRecord::MissingAttributeError error if you pass an attribute that does not exist in the model.

This can happen for a few reasons:

  1. You misspelled an attribute name

  2. You passed an attribute that has been removed from the model

  3. You passed an attribute that does not exist at all

For example:

  class Customer < ActiveRecord::Base
  end

  Customer.new(first_name: "John", lastt_name: "Doe") # typo, should be last_name
  #=> ActiveRecord::MissingAttributeError: missing attribute: lastt_name

Here we misspelled last_name as lastt_name, resulting in an error.

To handle this, you have a few options:

  1. Correct the attribute name

  2. Ignore the unknown attribute

  3. Raise a custom error

Correct the Attribute Name

The obvious solution is to simply fix the typo or misspelled attribute name.

Customer.new(first_name: "John", last_name: "Doe") # works!

Ignore the Unknown Attribute

You can tell Active Record to ignore unknown attributes when creating a record using with_unknown_attributes:

class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class
  self.abstract_class = true

  def self.with_unknown_attributes(attributes)
    create(attributes.slice(*column_names.map(&:to_sym)))
  end

end

customer = Customer.with_unknown_attributes(first_name: "John", lastt_name: "Doe")
customer.save # saves customer with first_name, ignoring lastt_name

Raise a Custom Error

You can rescue the ActiveRecord::MissingAttributeError and raise your own custom error:

  begin
    customer = Customer.new(first_name: "John", lastt_name: "Doe")
    customer.save
  rescue ActiveRecord::MissingAttributeError => e
    raise MyAppError, "Invalid attribute #{e.attribute}"
  end