开发者

output formated json with rails 3

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.fi开发者_JAVA技巧rstname} #{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 :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.


If Adam's response won't work for you, this may do it (admittedly not the most elegant solution):

{
    query:'<%= @query %>',
    suggestions: [<%= raw @customers.map{|c| "'#{c.firstname} #{c.lastname}'" }.join(", ") %>],
    data: [<%= raw @customers.map{|c| "'#{c.id}'" }.join(", ") %>]
}


I've seen something like this in a .erb:

<%= raw
  {
    :query       => @query,
    :suggestions => @customers.map{|c| "#{c.firstname} #{c.lastname}" },
    :data        => @customers
  }.to_json
%>

If thinking of preparing data to be consumed by other programs as presentation logic, this might make sense to you.

FWIW I like it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜