简体   繁体   中英

Rails :before_save upcase private method

I have two methods in my model which makes changes to the registration field before inserting it in to the DB. The strip_whitespace method works. However, the make_uppercase does not.

I have also tried passing just the make_uppercase method to the before_save callback. Any help would be appreciated.

class Vehicle < ActiveRecord::Base
  belongs_to :vehicle_class
  belongs_to :vehicle_make

  before_save :strip_whitespace, :make_uppercase

  # Strip whitespace from registration field before inserting it in to the DB
  def strip_whitespace
    self.registration.gsub!(/\s+/, '')
  end

  # Make all characters uppercase before inserting it in to the DB
  def make_uppercase
    self.registration.upcase
  end

  private :strip_whitespace, :make_uppercase

end

I think you should use upcase! and not just upcase

or redefine the method like that:

def make_uppercase
  self.registration = self.registration.upcase
end

Try:

def make_uppercase
  self.registration.upcase!
end

The bang method (upcase!) modifies the receiver - in this case self.registration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM