I use rails 3.0.3
A javascript auto complete needs data like this
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
}
My action is
def autocomplete
@query = params[:query]
@customers = Customer.where('firstname like ?', "%#{@query}%")
render :partial => "customers/autocomplete.json"
end
My view is
{
query:'<%= @query %>',
suggestions: <%= raw @customers.map{|c| "#{c.firstname} #{c.lastname}" } %>,
data: <%= raw @customers.to_json %>
}
it returns
{
query:'e',
suggestions: ["customer 1", "customer 2"],
data: [1, 3]
}
it’s not working because the data for suggestions/data should be between simple quote…
I cannot use the to_json method, because it’ll returns all the content of my object.
Any suggestion?
cheers
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
:onlyor:exceptto exclude what you don’t want.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
Hashobject:I’ve tried using partials to build json responses, but that doesn’t work nearly as well as simply using
Hashto 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:
Just some convenience functions that makes your life a little easier, and your controllers/views cleaner.