Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: before_save fields to lowercase

Tags:

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
like image 844
user3673826 Avatar asked May 25 '14 14:05

user3673826


People also ask

How do you change uppercase to lowercase in Ruby?

Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase : "hello James!". downcase #=> "hello james!"

What does .save do in Ruby?

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.

Does Ruby have Upcase?

Symbol#upcase() : upcase() is a Symbol class method which returns the uppercase representation of the symbol object.


3 Answers

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.

like image 150
Gergo Erdosi Avatar answered Oct 12 '22 23:10

Gergo Erdosi


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! }
like image 40
Vinicius Brasil Avatar answered Oct 12 '22 23:10

Vinicius Brasil


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.

like image 22
hjing Avatar answered Oct 13 '22 00:10

hjing