【问题标题】:output formated json with rails 3使用rails 3输出格式化的json
【发布时间】:2011-05-20 16:31:13
【问题描述】:

我使用 Rails 3.0.3

JavaScript 自动完成需要这样的数据

{
 query:'Li',
 suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
 data:['LR','LY','LI','LT']
}

我的行动是

  def autocomplete
    @query = params[:query]
    @customers = Customer.where('firstname like ?', "%#{@query}%")
    render :partial => "customers/autocomplete.json"
  end

我的看法是

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

它返回

{
    query:'e',
    suggestions: ["customer 1", "customer 2"],
    data: [1, 3]
}

它不起作用,因为建议/数据的数据应该在简单的引号之间......

我不能使用 to_json 方法,因为它会返回我的对象​​的所有内容。

有什么建议吗?

干杯

【问题讨论】:

    标签: ruby-on-rails json serialization ruby-on-rails-3


    【解决方案1】:

    注意:这已经过时了,Jbuilder 是一个更好的选择。


    有两种方法可以解决这个问题。如果您只需要对象中的字段子集,则可以使用:only:except 排除您不想要的字段。

    @customer.to_json(:only => [:id, :name])
    

    在您的示例中,您似乎需要以特定格式返回 json,因此简单地序列化结果数组是行不通的。创建自定义 json 响应的最简单方法是使用 Hash 对象:

    render :json => {
      :query => 'e',
      :suggestions => @customers.collect(&:name),
      :data => @customers.collect(&:id)
    }
    

    我尝试过使用 partials 来构建 json 响应,但这并不像简单地使用 Hash 那样有效。


    将名字和姓氏格式化为单个字符串在您的视图中可能会做很多事情,我建议您将其移至函数中:

    class Customer < ActiveRecord::Base
      ...
      def name
        "#{first_name} #{last_name}"
      end
    
      def name=(n)
        first_name, last_name = n.split(' ', 2)
      end
    end
    

    只是一些方便的功能,让你的生活更轻松,你的控制器/视图更干净。

    【讨论】:

      【解决方案2】:

      如果亚当的回应对你不起作用,这可能会起作用(诚然不是最优雅的解决方案):

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

      【讨论】:

      • 感谢您的回复,如果我使用 @customers.collect{|c|,Adam 的解决方案就有效"#{c.firstname} #{c.lastname}"}
      【解决方案3】:

      我在 .erb 中看到过类似的内容:

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

      如果考虑准备数据以供其他程序使用作为表示逻辑,这可能对您有意义。

      FWIW 我喜欢它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-29
        • 2015-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多