[英]Model Attribute Fetched as Nil, when value is not nil
If I set a value for a model attribute, it is saved correctly.如果我为 model 属性设置一个值,它会被正确保存。
I have a model我有一个 model
# gem 'rails', '6.1.3'
class Start < ApplicationRecord
end
s = Start.find(465860)
s.gear_change = 'test value'
s.save!
s.gear_change
=> nil
s
=> #<Start id: 465860, gear_change: "test value">
Why is rails returning nil?为什么 Rails 返回 nil?
There could be another column called gear
in your database.您的数据库中可能还有另一个名为gear
的列。 And gear_change
could be the Active Record dirty method being called on the gear
attribute. gear_change
可能是在gear
属性上调用的Active Record 脏方法。 Since the gear
attribute has not changed, the gear_change
dirty method returns nil
.由于gear
属性没有改变, gear_change
dirty 方法返回nil
。
One solution would be to access the gear_change
attribute as a hash value - s[:gear_change]
or s['gear_change']
.一种解决方案是将gear_change
属性作为 hash 值访问 - s[:gear_change]
或s['gear_change']
。
It is possible that you have overridden the gear_change
method in your model somewhere which is returning nil
.您可能在 model 的某处覆盖了gear_change
方法,该方法返回nil
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.