Bala Karthik Bala Karthik - 5 months ago 10
JSON Question

Altering JSON response in rails?

I have a model named User and in many actions i am rendering the response as json. for ex while showing the user data, i am using


@user = User.find_by_id(params[:id])
render json: {data: @user}


Now i have a requirement that while responding user data i need to show only last 2 digit of the mobile number for ex) ********78, is there any way to achieve this, Because altering the response in each action will be too difficult so is there any way to write a common method for handling this situation.

Answer

You can write a method in user model

user.rb

def as_json(options = {})
  # use options as per need
  {id: self.id, name: self.name, mobile: mask}
end

def mask
  # masking logic
end

You can write a method which masks the initial characters and do render json: {data: @user.as_json)}

Checkout this link