I use rails 3.0.3
A javascript auto complete needs data like this
{
query:\'Li\',
suggestions:[\'Liberia\',\'Libyan Arab Jamahiriya\',\'Liechtenstein\'
Note: this is way out of date, Jbuilder is by far a better option.
There are two ways you can approach this. If you simply need a subset of the fields in an 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 simply serializing an array of results won't work. The easiest way to create a custom json response is with the Hash
object:
render :json => {
:query => 'e',
:suggestions => @customers.collect(&:name),
:data => @customers.collect(&:id)
}
I've tried using partials to build json responses, but that doesn't work nearly as well as simply using Hash
to do it.
Formatting the first and last names as a single string is something you are likely to do a lot in your views, I would recommend moving that to a function:
class Customer < ActiveRecord::Base
...
def name
"#{first_name} #{last_name}"
end
def name=(n)
first_name, last_name = n.split(' ', 2)
end
end
Just some convenience functions that makes your life a little easier, and your controllers/views cleaner.