Chen Yangjian's Blog

Carpe diem - Seize the day

ActiveModle 的一个小 Gotcha

| Comments

错误信息:

ActiveModel::MissingAttributeError in ComponentsController#update
missing attribute: name

提示错误的源头是 model 里头通过 after_find 注入的方法中,self.name 这句挂掉了。name 属性自然是有定义的,这就让人很摸不着头脑。

tl;dr 的请看:在出错的方法里头加一句判断

return unless self.attribute_present?(:name)

就可以了。

第一次碰上这个的时候很无厘头,后来发现是当 model 的 validation 流程挂掉的时候才出现的。一开始向暴力解决问题,便加上一句 self.instance_variable_defined?(:@name) 期待能解决问题,然而这句实实在在的返回的是 false。然后 self.inspect 一下,才晓得 ActiveRecord 类中对数据库中的字段属性并不是直接以类变量定义的,要查看模型中是否有相应的字段,得用 self.attribute_present?(:name)。inspect 的时候,还顺带找到了错误根源,当 model.save 挂掉的时候,rails 不知道搞什么,要去找导致错误的另一个 model (当校验 uniqueness 的时候)。而且该 model 返回的数据里头除了 id 属性神马也没有。但是也会去调 after_find,于是就挂了。

Comments