handle unknown attributes in activeRecord
Table of contents
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:
You misspelled an attribute name
You passed an attribute that has been removed from the model
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:
Correct the attribute name
Ignore the unknown attribute
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
Subscribe to my newsletter
Read articles from 黄滚 directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
黄滚
黄滚
I am founder of https://some.im