2

I have model User. User contain :name and :second_name fields. I define function in model

def full_name
    self.name + ' ' + self.second_name
end

When I call to_json() method on user object i get {name: '...', second_name: '...'}. How I add to result full_name field?

2 Answers 2

2

How about defining as_json method in your User model and overriding the default behaviour of to_json.

So this will become:

def as_json(options)
  super(:methods => [:full_name])
end 

For reference also see: http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html

Sign up to request clarification or add additional context in comments.

1 Comment

As Bryan notes, this is clean and allows you to call multiple class methods. Additionally you can also exclude items that are unnecessary by adding except in your options
1

Override .as_json in your User model, add following lines to your user model:

def as_json(options)
  super.merge({
      full_name: "#{self.name} #{self.second_name}"
  })
end

And in your controller, just write: render @user, don't explicit call .to_json

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.