[ACCEPTED]-Ruby on Rails: before_save fields to lowercase-activerecord
downcase
returns a copy of the string, doesn't modify 2 the string itself. Use downcase!
instead:
def downcase_fields
self.name.downcase!
end
See documentation for 1 more details.
You're not setting name
to downcase by running 3 self.name.downcase
, because #downcase
does not modify the string, it 2 returns it. You should use the bang downcase
method
self.name.downcase!
However, there's 1 another way I like to do it in the model:
before_save { name.downcase! }
String#downcase
does not mutate the string, it simply returns 7 a modified copy of that string. As others 6 said, you could use the downcase!
method.
def downcase_fields
name.downcase!
end
However, if 5 you wanted to stick with the downcase
method, then 4 you could do the following:
def downcase_fields
self.name = name.downcase
end
This reassigns 3 the name instance variable to the result 2 of calling downcase on the original value 1 of name.
Other simple example with less code:
class Transaction < ActiveRecord::Base
validates :name, presence: true
validates :amount, presence: true, numericality: true
before_save { self.name.downcase!}
end
Hope 1 this helps!
You need to use exclamation mark after calling 4 method downcase, if you also want to save result 3 of operation to the variable. So for you 2 will be usable:
self.name.downcase!
Don't forget that .downcase! replacement 1 works only in ASCII region.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.