【问题标题】:Nesting :json include in Rails嵌套 :json 包含在 Rails 中
【发布时间】:2012-04-02 20:34:59
【问题描述】:

我有三个模型:

class A < ActiveRecord::Base
  has_many :bs
end

class B < ActiveRecord::Base
  has_one :c
  belongs_to :a
end

class C < ActiveRecord::Base
  belongs_to :b
end

我想获取包含 A 的所有 B 和 C 的 json 数据。我尝试了许多类似于:

render json: @as, :include => [:bs => [:include=>[:c]]

但没有任何效果。有什么好的方法可以做到这一点。

【问题讨论】:

    标签: ruby-on-rails-3 json


    【解决方案1】:

    请参阅 ActiveModel::Serializers::JSON#as_json 以查看您可以传递给 render :json 的选项。去引用:

    要包含关联,请使用:include ...

    二级和更高级别的关联也可以工作:

    user.as_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" } ]
    #    }
    

    不必直接调用to_jsonas_jsonrender :json 会自动调用。

    【讨论】:

    • 如果你卡在 Rails 2 中,render() 不支持:include,但to_json() 支持。在这种情况下,调用render :json =&gt; @as.to_json(:include =&gt; :bs) 是有意义的。
    • to_json 有时会破坏嵌套结构
    • @Albert.Qing 如果您遇到特定问题,您应该将其作为新问题发布。
    【解决方案2】:

    你需要传入哈希而不是数组

    render :json => @as.to_json(:include => { :bs => {:include =>:c} })
    

    【讨论】:

      【解决方案3】:

      试试

      render :json => @as.to_json(:include => {:bs => :c})
      

      【讨论】:

        【解决方案4】:

        试试这个:

        render json: @tiquets, :include => { :enterprise => {:include => { :location => {:only => :lo_name } },:only => :en_name } } }
        

        【讨论】:

        • @OwaisKureshi 仅代码的答案可能不是一个好的答案,但它仍然是一个答案。我会向你推荐这篇关于 LQPRQ 的帖子:You're doing it wrong: A plea for sanity in the Low Quality Posts queue
        • @FelixSFD ,我同意,但是应该有一些文字解释答案,或者他可以将其作为评论发布?
        • @OwaisKureshi 建议并且最好稍微解释一下代码。但即使没有解释,这也是一个答案。
        • @FelixSFD 好的,我明白你的意思了,谢谢你的解释,我已经撤回了我的评论。
        【解决方案5】:

        对于那些想要做同样事情但使用 ruby​​ 的新语法的人来说,它会是这样的

        render json: @as.to_json(include: { bs: { include: :c}})
        

        并且只提取一些属性:

        render json: @a.to_json(only: [:name, :phone, :phone_mobile], include: { bs: { only: :email, include: {c: {only: [:id, :name]}}}})
        

        【讨论】:

          【解决方案6】:

          试试这个:

          render json: @as.to_json(include:{bs: {include:{c:}}})
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多