output formated json with rails 3

后端 未结 3 1220
说谎
说谎 2021-02-06 18:10

I use rails 3.0.3

A javascript auto complete needs data like this

{
 query:\'Li\',
 suggestions:[\'Liberia\',\'Libyan Arab Jamahiriya\',\'Liechtenstein\'         


        
3条回答
  •  暖寄归人
    2021-02-06 18:48

    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.

提交回复
热议问题