Mridang Agarwalla
Mridang Agarwalla

Reputation: 44978

Strip spaces when inserting a record into Rails

I have a table in Rails with just one column called :name. When inserting a record into this table, I would like to strip all the spaces from the text and change it to upper case. Where would i write this method — in the Model file? What method would I have to override? When inserting data into this Model, I'm using a method called find_or_create_by_name.

Upvotes: 0

Views: 307

Answers (1)

Jimmy
Jimmy

Reputation: 37081

Use an ActiveRecord callback. It might look like this:

class MyModel < ActiveRecord::Base
  before_save :strip_and_upcase_name

  def strip_and_upcase_name
    self.name.strip!
    self.name.upcase!
  end
end

Upvotes: 4

Related Questions