【问题标题】:Include and group JSON by parent model按父模型包含和分组 JSON
【发布时间】:2015-06-05 15:01:26
【问题描述】:

我目前正在调用 API 来获取出版商的图书。然后,我将每本书分组到各自不同的故事弧中。一切正常,我能够在我的应用程序中检索 JSON。

但是,我想更改我当前的 JSON 响应并删除 JSON 根弧:

有人知道如何删除 JSON 根并指定我想要的图书属性吗?

另外,一个 :has many => 通过关联有助于简化这一点并按照我想要的方式分组吗?

这是我的代码。

模型

class Publisher < ActiveRecord::Base
  has_many :books
end

class Arc < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :arc
  belongs_to :book
end

当前 Json

{
  "arcs": [
    {
     "books": [
       {
        "arc_id": 1,
        "created_at":"2014-12-27T20:54:46.518Z",
        "id": 311,
        "publisher_id": 7,
        "updated_at":"2015-06-04T20:55:28.190Z"
       }
     ],
     "id": 1,
     "name": "One-Shot"
   }
  ]
}

我怎样才能把它改成这个?

[
  {
     "books": [
       {
        "arc_id": 1,
        "id": 311,
        "publisher_id": 7
       }
     ],
     "id": 1,
     "name": "One-Shot"
  }
]

控制器

  def index
    @publisher = Publisher.find(params[:publisher_id])
    @books = @publisher.books.order("positioning")

    @results = {arcs: []}
    @books.group_by(&:arc).each do |arc, books|
      @results[:arcs] << {
        id: arc.id,
        name: arc.name,
        books: books
      }
    end

    respond_to do |format|
      format.html
      format.json { render :json => @results.to_json }
    end
  end 

我也尝试在下面的链接中使用 rabl,但它不起作用.. https://stackoverflow.com/questions/30660136/include-group-by-parent-model-json-rabl

【问题讨论】:

    标签: ruby json api ruby-on-rails-4 group-by


    【解决方案1】:

    你可以在没有arcs 的情况下直接渲染回来,例如

    format.json { render :json => @results[:arcs].to_json }
    

    话虽如此,您也可以将控制器方法更改为此,但您必须更改 html 响应处理 @results 的方式:

    def index
      @publisher = Publisher.find(params[:publisher_id])
      @books = @publisher.books.order("positioning")
    
      @results = @books.group_by(&:arc).map do |arc, books|
        {  
          id: arc.id,
          name: arc.name,
          books: books
        }
      end
    
      respond_to do |format|
        format.html
        format.json { render :json => @results.to_json }
      end
    end 
    

    这也将为您提供所需的结果,因为在这种情况下,map 只会返回您设计的Hashes 的Array

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多