【问题标题】:Including nested objects in JSON response, from MongoMapper objects在 JSON 响应中包含嵌套对象,来自 MongoMapper 对象
【发布时间】:2011-02-24 17:19:48
【问题描述】:
class Api::StoresController < ApplicationController  
  respond_to :json

  def index
    @stores = Store.all(:include => :products)
    respond_with @stores
  end
end

只返回没有产品的商店,

Store.find(:all).to_json(:include => :products)

关联已经过测试,我可以在控制台输出中看到嵌套产品,例如,

Store.first.products

让他们的产品包含在 MongoMapper 中的正确方法是什么?

这是我的模型:

   class Store
     include MongoMapper::Document         
     many :products, :foreign_key => :store_ids 
   end

   class Product
     include MongoMapper::Document         
     key :store_ids, Array, :typecast => 'ObjectId'
     many :stores, :in => :store_ids
   end

更新

在尝试 Scott 的建议时,我在 Store 模型中添加了以下内容:

def self.all_including_nested
  stores = []
  Store.all.each do |store|
    stores << store.to_hash
  end
end

def to_hash
  keys = self.key_names
  hash = {}
  keys.each{|k| hash[k] = self[k]}
  hash[:products] = self.products
  hash[:services] = self.services
  hash
end

在控制器中:

def index
  @stores = Store.all_including_nested
  respond_with @stores
end

哪个看起来应该可以工作?假设哈希数组会调用#to_json,然后每个哈希和每个产品+服务都会发生同样的情况。我正在阅读 ActiveSupport::JSON 的源代码,到目前为止,这就是我从中得到的。

但是,还没有工作... :(

【问题讨论】:

    标签: ruby-on-rails json mongomapper responders


    【解决方案1】:

    看看as_json() 方法。你把它放在你的模型中,定义你的 json,然后简单地调用 render :json 方法并得到你想要的。

    class Something
      def as_json(options={})
        {:account_name       => self.account_name,
         :expires_on         => self.expires_on.to_s,
         :collections        => self.collections,
         :type               => "Institution"}
      end
    end
    

    您会注意到self.collections 这是一个多关系。该模型还定义了as_json()

    class Collection
      def as_json(options={})
        {:name          => self.name,
         :title         => self.title,
         :isbn          => self.isbn,
         :publisher     => self.publisher,
         :monthly_views => self.monthly_views}
      end
    end
    

    这个包含self.monthly_views,代表另一个多关系。

    然后在你的控制器中:

    @somethings = Something.all
    render :json => @somethings
    

    【讨论】:

    • 在时间的紧要关头,刚刚想到了同样的问题,并打算用它来更新问题;)非常感谢您的回复,谢谢
    【解决方案2】:

    您可能必须创建自己的方法来生成散列,然后将散列转换为 JSON。我在想这样的事情:

    store = Store.first
    keys = store.key_names
    hash = {}
    keys.each{|k| hash[k] = store[k]}
    hash[:products] = store.products
    hash.to_json
    

    【讨论】:

    • 谢谢,这是有道理的——刚刚发现 :include 选项仅适用于 active_record 的 to_json。让这适用于单个实例,实现 Store#to_json (只需删除 hash = keys... 分配),但仍然必须弄清楚如何为集合执行此操作。厌倦了修补 mongo_mapper 本身:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    相关资源
    最近更新 更多