我遵循这个模式,以确保我的所有属性在保存之前都是规范化的:
class MyModel < ApplicationRecord
before_validation :normalize_attributes
def normalize_attributes
self.name&.strip!
self.email&.strip!
end
end
我还有一些更复杂的:
def normalize_attributes
# Transform to array if it is a string with things
# separated by comas
if self.favorite_things.is_a? String
self.favorite_things = self.favorite_things.split(",").map(&:strip)
end
end
它可以工作,但问题是当我把这个属性添加到serialized
个属性中时,它失败了:
serialize :favorite_things, Array
就像这里:
my_model.update(favorite_things: "ONE, TWO, THREE")
错误:
Error:
ActiveRecord::SerializationTypeMismatch: can't serialize `favorite_things`: was supposed to be a Array, but was a String. -- "ONE, TWO, THREE"
serialize
命令在before_validation
之前执行.
如何在序列化属性之前对属性进行清理?