Note : this is an obsolete option, Jbuilder is the best option. p>
There are two ways to approach this. If you just need a subset of the fields in the object, you can use :only or :except to exclude what you don't want.
@customer.to_json(:only => [:id, :name])
in your example, it looks like you need to return json in a specific format, so just serializing the array of results will not work. The easiest way to create a custom json response is with a Hash object:
render :json => { :query => 'e', :suggestions => @customers.collect(&:name), :data => @customers.collect(&:id) }
I tried using partials to create json responses, but this does not work much the same way as just using Hash for this.
Formatting the first and last names as a single line is something you are likely to do a lot in your views, I would recommend moving this to a function:
class Customer < ActiveRecord::Base ... def name "
Just some handy features that make your life a little easier and your controllers / views cleaner.
source share