Including methods and associations in a JSON Data set with Rails 1

Posted by Randy on October 02, 2009

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
end
 
class Employee < ActiveRecord::Base
  belongs_to :client
 
  def full_name
    "#{first_name} #{last_name}"
  end
end

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 ]
        }
      }
    ) }
  end
end

You will end up with the following data set:

{ client: { name: "Some client", employee: { email: "test@test.com", 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.

ActiveRecord – Making :include and :select play nice!

Posted by Randy on May 20, 2009

So I have been using a nice plug-in that will allow me to using :select when using :include, and not have it pull the entire data set. You can add the plug-in to your app like this:

script/plugin install git://github.com/blythedunham/eload-select.git

Here are some ways to use the plug-in:

Employee.find :all,
    :select => 'addresses.city, address.state, employees.*',
    :include => :address
Employee.find :first,
    :select => 'now() as current_time, addresses.city, DATE(addresses.created_at) as addresses.created_at, employee.*',
    :include => :address
Employee.find :all,
    :select => 'addresses.city, employees.name, employees.start_date',
    :include => :address

Examples taken from:
http://www.snowgiraffe.com/tech/329/eager-loading-select-plugin-when-select-plays-nice-with-include/