2

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 ?

1
  • What is the value of User.last.mobile before the update? And do you have any database defaults set for the column? Commented Jan 28, 2021 at 19:26

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.