Q:

How to strip column values in Active record through loop before saving in rails framework?

I have to remove spaces for every record before saving into the database.
I can do that by specifying it for each column, but when there 100 columns in each record, it is a pain and no of lines of code increases enormously.
Need help in changing the code into a loop, but being an amateur in rails I am not able to complete it.
class hello < ActiveRecord::Base

before_validation :remove_spaces  

def remove_spaces
          self.login = self.login.strip if self.login.present?
          self.email = self.email.strip if self.email.present?
          . so on .......

      end

end

A:

I would is attributes.each to iterate over all attribute names and the values of the current instance (while ignoring the attribute names). For each value I would call try(:strip!) to strip whitespace from the value. Please note that try only calls strip! on values that actually respond_to strip (that means basically just strings), therefore it would ignore nil values or values of unsupported types - like timestamps or booleans.
before_validation :sanitize_strings

private
def sanitize_strings
  attributes.each { |_, value| value.try(:strip!) }
end

Or when you only want to sanitize specific attributes then you can just iterate over their names:
ATTRIBUTES_TO_SANITIZE = %i[name title description]

def sanitize_strings
  ATTRIBUTES_TO_SANITIZE.each { |attr| send(attr).try(:strip!) }
end

