ruby-on-railsrubyrails-activerecordrails-models

Ruby on rails return a string if a model attribute is nil


I have a user model that has one profile. The profile has attribute such as name, gender, age, dob, designation. No fields in profile are mandatory. The user is created by an admin from only an email address and a password. All the profile fields are nil when user is created. Once the user is created he can sign up and edit his profile. When we go to user profile I want to show the user details and if a detail is not set, I want to show a 'not set'.

The go to approach would be to override the attributes in the profile model like:

def name
  super || 'not set'
end
def age
  super || 'not set'
end
//and so on 

but doing so creates a lot of code duplication. Doing <%= @user.name || 'not set'%> in the view also results in a lot of code duplication.

I have thought of including 'not set' as a default value for all the attributes in the migration but some of the fields are integer and date, so its not feasible and moreover we cannot add translation.

I looked into ActiveRecord Attributes and tried to set the default value to my string

class Profile < ApplicationRecord
attribute :name, :string, default: "not set"

but this is same like assigning the default value in the rails migration and doesn't work for other data types.

I am hoping for a method that can do something like

def set_default(attribute)
  attribute || 'not set'
end

Such scenarios must be quite common but I was quite surprised to not find any questions relating to this, here on stackoverflow or other places. I googled quite a lot but couldn't find a solution. Any links are also greatly appreciated.


Solution

  • Maybe some metaprogramming?

    class YourModel
      %w(name age).each do |a| # Add needed fields
        define_method(a) do
          super() || 'not set'
        end
      end
    end
    

    This could be extracted to a concern and include it where you need it.