Including methods and associations in a JSON Data set with Rails

I was poking around while working with creating an application specifically for web services. We decided to use JSON as the methods of transportation of data, but the problem came when I wanted to include custom methods, or associations in my data set. The solution was fairly simple, using the to_json method. Suppose you have the following classes:

class Client < ActiveRecord::Base
  has_many :employees

class Employee < ActiveRecord::Base
  belongs_to :client

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

We want the controller to return a client with association employees and the full name in the database. Here is how we would go about doing that:

def show
  @client = Client.find(params[:id])

  respond_to do |format|
    format.json { render :json => @client.to_json(:include => { :employee => { :only => :email, :methods => [:full_name]}})}

You will end up with the following data set:

  client: {
    name: "Some client",
    employee: {
      email: "",
      full_name: "John Doe"

Forgive me if I messed up the json output…doing it from memory 🙂 There are of course way easier uses for this too, but I just decided to spit out a more complex one.

4 thoughts on “Including methods and associations in a JSON Data set with Rails

  1. Great Tutorial man, i like it.

    can u post sample tutorial using both extjs and rails like sending data to extjs vice-versa.

Leave a Reply

Your email address will not be published. Required fields are marked *