ActiveRecord attribute_present?谎言。我该如何解决?

ActiveRecord attribute_present? lies. How can I fix it?

docs for attribute_present? 说:

Returns true if the specified attribute has been set by the user or by a database load ...

但是……那不是真的!我们看到 here Rails 从数据库默认值初始化新对象的属性。

所以,假设我们有一个用户 table 和 age not null default 0。那么

User.new.attribute_present?(:age) == true

但它不是我们设置的或数据库负载。

也许我在争论语义,但无论如何,我想要一种方法如其所言:告诉我字段是否已 显式设置

例如

u = User.new
# u.attribute_set?(:age) == false
u.age = u.age #set explicitly to default, for example
# u.attribute_set?(:age) == true

存在吗?

据我所知,没有办法(前提是你的数据库中有默认参数)(好的设计)

已编辑:根据下面 Z5h 的评论从原始答案编辑