3

This is the code in my People Controller for the Create action :

def create
  @person = Person.new(person_params)
  @person.branch_id = session[:branch_id]
  @person.added_by = current_user.id
  if @person.save
    respond_to do |format|
      format.json { render json: @person}
    end
  end
end

And I have a method in my Person Model to get the person's full name :

def full_name
    [self.first_name, self.middle_name, self.last_name].reject(&:blank?).join(" ")
end

What is the best way to add the Person's full name to @person when it is returned back as a JSON object

3 Answers 3

5

As you want it to be in the JSON you could just override the as_json method of the Person class to include the options to add the full_name method:

def as_json(options = {})
  super options.merge(methods: [:full_name])
end

This method is used by Rails whenever an object should be serialized into a JSON string, for example by render json: @person. If you only want to add the extra method on this single occasion you can also call it directly inline using render json: @person.as_json(methods: [:full_name]) or if you want to make more complex customizations to the JSON output you could think about using dedicated serializer classes, for example by using the ActiveModel::Serializers gem. However, as you only want to add one method and that probably everywhere you are serializing @person, the best way for your case would be to just override as_json as described in the beginning.

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

Comments

1

Try this

@person.as_json(methods: :full_name)

Comments

0

Check out this article: http://www.tigraine.at/2011/11/17/rails-to_json-nested-includes-and-methods

It's got instructions for doing exactly what you're trying to do, the short story being that you need to pass in :my_method => full_name to the json rendering.

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.