Rails 5, model all fields in capital letters

0

In ASP NET MVC I can create a class library where I have help classes for different situations (date conversion, encryption, etc.), but I have a specific one that receives my model and goes through the properties and those that are type String passes them to uppercase, so I do something like this:

ClientesLogica.Save(Helpers.ViewModelToUpper(model));

How can I do something similar in Rails, and not have to do it field by field?

    
asked by Leonardo Velazquez 20.05.2018 в 20:18
source

1 answer

0

The logic can be put in different places, depending on the specific purpose.

For example, if you want the values to be modified before being saved in the database, you would do it directly in your model:

class ViewModel < ApplicationRecord
  before_save :to_upper

  private
  def to_upper
    attributes.keys.each do |attribute|
      self[attribute].try(:upcase!)
    end
  end
end

In this way the fields will be changed to uppercase each time the record is saved / updated in the database.

If you plan to use it for more than one model, you can add the method in class ApplicationRecord :

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  private
  def to_upper
    attributes.keys.each do |attribute|
      self[attribute].try(:upcase!)
    end
  end
end

class ViewModel < ApplicationRecord
  before_save :to_upper
end
    
answered by 20.05.2018 / 21:07
source