【问题标题】:How to handle two nested siblings, with to_json next?如何处理两个嵌套的兄弟姐妹,接下来是 to_json?
【发布时间】:2013-06-01 19:58:41
【问题描述】:

to_json ActiveRecord 文档说 this 用于处理两个嵌套模型,其中 cmets 嵌套在帖子中:

  konata.to_json(:include => { :posts => {
                                 :include => { :comments => {
                                               :only => :body } },
                                 :only => :title } })
  # => {"id": 1, "name": "Konata Izumi", "age": 16,
        "created_at": "2006/08/01", "awesome": true,
        "posts": [{"comments": [{"body": "1st post!"}, {"body": "Second!"}],
                   "title": "Welcome to the weblog"},
                  {"comments": [{"body": "Don't think too hard"}],
                   "title": "So I was thinking"}]}

假设我有两个嵌套的模型,但没有深度嵌套。可以说它是用户模型和 cmets 模型。嵌套模型就是我所说的嵌套兄弟。

我希望我的 json 看起来像这样:

x = { 
    "Blog": {
        "Comments": [
         {"id":1,"name":"John Doe"},
         {"id":2,"name":"Don Joeh"}
        ],
        "User": [
         {"id":2,"company":"ACME"},
         {"id":4,"company":"BUD"}]
    }
}

当我两次使用 include 方法时,我最终得到的是一系列深度嵌套的 json,其中用户是 cmets 的子级。怎么了?!

data.to_json(
        :include => { :blog => {
          :include => [{ :comments => {
            :except => SKIPPED_COLUMNS,
            :methods => [:_type]
          }},
          { :users => {
              :except => SKIPPED_COLUMNS,
              :methods => [:_type]
          }}],
          :except => SKIPPED_COLUMNS,
          :methods => [:_type]
        }},
        :except => SKIPPED_COLUMNS,
        :methods => [:_type]
      )

【问题讨论】:

    标签: ruby-on-rails ruby activerecord include to-json


    【解决方案1】:

    为什么你有两次blog

    blog.to_json(
        :include => { :blog => {
    

    我认为,第二个blog 不应该在那里。试试这个:

    blog.to_json(
      :include => [
        {
          :comments => {
            :except => SKIPPED_COLUMNS,
            :methods => [:_type]
          }
        }, {
          :users => {
            :except => SKIPPED_COLUMNS,
            :methods => [:_type]
          }
        }
      ],
      :except => SKIPPED_COLUMNS,
      :methods => [:_type]
    )
    

    【讨论】:

    • 这只是一个错字。它实际上存储在数据中
    猜你喜欢
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2012-07-23
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    相关资源
    最近更新 更多