Bala Karthik Bala Karthik - 1 year ago 87
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 Source

You can write a method in user model


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

def mask
  # masking logic

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

Checkout this link

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download