[ACCEPTED]-Ruby on Rails: before_save fields to lowercase-activerecord

Accepted answer
Score: 35

downcase returns a copy of the string, doesn't modify 2 the string itself. Use downcase! instead:

def downcase_fields

See documentation for 1 more details.

Score: 7

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


However, there's 1 another way I like to do it in the model:

before_save { name.downcase! }
Score: 4

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

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

This reassigns 3 the name instance variable to the result 2 of calling downcase on the original value 1 of name.

Score: 3

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!}


Hope 1 this helps!

Score: 1

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:


Don't forget that .downcase! replacement 1 works only in ASCII region.

More Related questions