【问题标题】:Rails 3 eager load and include attributes from association in json or xmlRails 3 急切加载并在 json 或 xml 中包含关联的属性
【发布时间】:2014-11-07 00:51:24
【问题描述】:

对于我的 API,我需要预先加载所有客户端、客户端项目及其价格,并将它们作为 JSON 或 XML 返回。

Model Client
has_many items

Model Item
belongs to :client
has_many :prices

Model Price
belongs_to :item

我需要使用来自所有三个关联的所有属性构建一个分层结果@tree,每个客户 -> 每个项目 -> 每个价格作为 API 调用的 JSON 和 XML 响应发送回。

所以:

@tree =  Client_1
         --Item_1
           --Price_1
           --Price_2
         --Item_2
           --Price_3
           --Price_4
         Client_2
         ... and so on
        respond_to do |format|
        format.xml {render :xml =>{@tree}}
        format.json {render :json =>{@tree}}
        end

更新::

我已经尝试过包含、连接、预加载 eager_load 和其他一切。所有这些只带来最顶层模型的属性,即客户端。它们不会从关联中加载属性。我什至尝试过Retrieve all association's attributes of an AR model?。它在某种程度上做了我需要的,但不是全部。它没有将@tree 放在我需要的层次结构中。它像

一样创建它
@tree =  Client_1
         --Item_1
         --Item_2
         --Price_1
         --Price_2
         --Price_3
         --Price_4

这不是我需要的。

【问题讨论】:

  • 你试过什么。您是否将 eager_loadinclude 视为查询方法?甚至有一些方法可以将其构建到模型中,因此如果这是您的意图,这些总是急切地加载,但不知道您自己尝试过,我宁愿不只是为您解决问题。

标签: ruby xml json ruby-on-rails-3 activerecord


【解决方案1】:

【讨论】:

    猜你喜欢
    • 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
    相关资源
    最近更新 更多