Search code examples
ruby-on-railsmodels

Rails 4 - Titleize on read, downcase on save, in model


I'm sure it's a pretty dumb question but I can not figure it out.

In my user model I have a

`before_save :downcase_username` #because I use custom subdomain for each user with request

def downcase_username
  self.username = username.downcase
end

However, I would like to titleize the username each time it is visible (read?) in view without specifying each time user.username.titleize. I do not know which before_ to call inside model, in controller I would have use a before_action. Moreover, Is there a way to automate this for all the values of a model ? (always titleize just in view)

Any hint appreciated.

Thank you very much


Solution

  • You could make a custom getter...

    class User < ActiveRecord::Base
      def username
        self[:username].titleize
      end
    end
    

    If you want it only on reads for views but not on reads for edits then you might be better off using a decorator.

    https://github.com/drapergem/draper