Reputation: 6217
a Rails application has a sanitizing method
def mobile=(value)
super(value.to_s.gsub(/\s+/, "").to_i) unless value.nil?
end
Yet, when submitting via console the following
User.last.update(mobile: nil)
the record was obviously processed to_i
returning a 0
mobile: 0
implying that the syntax unless value.nil?
is inappropriate. How should the method be expressed to no fire when the value submitted is nil ?
Upvotes: 2
Views: 138
Reputation: 36880
Because you're only calling super
if the value is not nil, that means the value is NOT replaced when the value is nil. So if the value contained 0 then it'll still contain 0 afterwards.
If you want to be able to set the value to nil, you should do...
def mobile=(value)
super(
value.nil? ? nil : value.to_s.gsub(/\s+/, "").to_i
)
end
Upvotes: 1