Custom model method that should be included in JSON serialization

json, model, ruby-on-rails, ruby-on-rails-3

Solution

You can overwrite the to_json method in your model by passing `:methods` options and call `super`. This will call `as_json` version of the super class with `:methods` options so that it will serialize your model with `full_name` attributes.

class Person < ActiveRecord::Base
  def as_json(options={})
    options[:methods] = [:full_name]
    super
  end

  def full_name
    "#{first_name} #{last_name}"
  end
end

Inside your controller, you can simply

render :json => @person

Check this document out if you want to know more options that can pass to `as_json` method. http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html

Problem

I'm working with a javascript library where I build comboboxes. I have the requirement of build a combobox with full name of a person, so I mean name + surname. Because in database those are 2 separate field (and in my model too), I would like to know if there is a fast way (instead of manually build all hash objects) to "simulate" the presence of an additional field in my model for JSON conversion, because this object must be returned as a JSON array where you can read *full_name* as a key. Thanks for help

Original source

Related problems