Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom model method that should be included in JSON serialization

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

like image 393
Francesco Belladonna Avatar asked May 30 '12 17:05

Francesco Belladonna


1 Answers

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

like image 143
Chamnap Avatar answered Sep 19 '22 12:09

Chamnap