【问题标题】:flatten a key from a collection of ruby json objects从 ruby​​ json 对象集合中展平一个键
【发布时间】:2014-07-10 20:43:48
【问题描述】:

我有这个收藏:

[#<Admin id: 1, enabled: true, created_at: "2013-11-11 18:15:20", updated_at: "2014-05-21 23:16:06"]

当我打电话时

 render :json => @authors.sort_by {|author| author.enabled}

正如预期的那样,我得到了返回的 JSON:

[{"admin":{"created_at":"2013-11-11T18:15:20Z","enabled":true,"id":1,"updated_at":"2014-05-21T23:16:06Z"}}, {"admin":{}}]

有没有办法使用 rail 的渲染函数来展平 json,所以我的集合看起来像这样:

[{"created_at":"2013-11-11T18:15:20Z","enabled":true,"id":1,"updated_at":"2014-05-21T23:16:06Z"}, {}]

【问题讨论】:

    标签: ruby-on-rails ruby json render


    【解决方案1】:

    试试这个:

    render :json => @authors.sort_by {|author| author.enabled}.to_json
    

    【讨论】:

      【解决方案2】:

      尝试使用地图功能。

      render :json => @authors.sort_by{|author| author.enabled}.map{|a| a["admin"]}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-12
        • 1970-01-01
        • 2011-07-23
        • 2021-03-05
        • 2013-11-29
        • 1970-01-01
        • 2021-01-06
        相关资源
        最近更新 更多