output formated json with rails 3

后端 未结 3 1219
说谎
说谎 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.

    0 讨论(0)
  • 2021-02-06 19:06

    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(", ") %>]
    }
    
    0 讨论(0)
  • 2021-02-06 19:13

    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 讨论(0)
提交回复
热议问题