I'm trying to change the fields from the form to lower case before they get saved in the database. This is my code but the output from the database is still in upper case why isnt the code working?
class Transaction < ActiveRecord::Base
validates :name, presence: true
validates :amount, presence: true, numericality: true
before_save :downcase_fields
def downcase_fields
self.name.downcase
end
end
Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase : "hello James!". downcase #=> "hello james!"
The purpose of this distinction is that with save! , you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.
Symbol#upcase() : upcase() is a Symbol class method which returns the uppercase representation of the symbol object.
downcase
returns a copy of the string, doesn't modify the string itself. Use downcase!
instead:
def downcase_fields
self.name.downcase!
end
See documentation for more details.
You're not setting name
to downcase by running self.name.downcase
, because #downcase
does not modify the string, it returns it. You should use the bang downcase
method
self.name.downcase!
However, there's another way I like to do it in the model:
before_save { name.downcase! }
String#downcase
does not mutate the string, it simply returns a modified copy of that string. As others said, you could use the downcase!
method.
def downcase_fields
name.downcase!
end
However, if you wanted to stick with the downcase
method, then you could do the following:
def downcase_fields
self.name = name.downcase
end
This reassigns the name instance variable to the result of calling downcase on the original value of name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With