2012-10-29 16 views
0

我在rails 3應用程序中使用了mongoid 3。Mongoid render引用完整對象

我有引用的對象「文件的客戶端類(因此自定義 'LocalisedFile' 類的實例。)

Client.rb:

class Client 
    include Mongoid::Document 
    include Mongoid::Timestamps 
    store_in collection: 'clients' 

    field :name, type: String 

    has_many :files, class_name: 'LocalisedFile', inverse_of: :owner 
end 

LocalisedFile.rb:

class LocalisedFile 
    include Mongoid::Document 
    include Mongoid::Timestamps 
    include Geocoder::Model::Mongoid 
    store_in collection: 'files' 

    belongs_to :owner, class_name: 'Client', inverse_of: :files 
end 

管理我的文檔沒有問題。

但是,當我想渲染文件的數組,我只是得到與客戶端串ID的「owner_id」場...

[(2) 
    { 
     "_id": "508e85e412e86a2607000005", 
     "created_at": "2012-10-29T13:34:29Z", 
     "owner_id": "508c06e4bcd7ac4108000009", 
     "title": "Try", 
     "updated_at": "2012-10-29T13:34:29Z", 
    },- 
    { 
     "_id": "508e8c5312e86a2607000006", 
     "created_at": "2012-10-29T14:01:56Z", 
     "owner_id": "508c06e4bcd7ac4108000009", 
     "title": "2nd Try", 
     "updated_at": "2012-10-29T14:01:56Z", 
    }- 
] 

這也許很正常,但我想獲得客戶端信息,用它在與谷歌地圖API一個JS應用,如:

[(2) 
    { 
     "_id": "508e85e412e86a2607000005", 
     "created_at": "2012-10-29T13:34:29Z", 
     "owner": { 
      "_id": "508c06e4bcd7ac4108000009", 
      "name": "Client 1" 
     }, 
     "title": "Try", 
     "updated_at": "2012-10-29T13:34:29Z", 
    },- 
    { 
     "_id": "508e8c5312e86a2607000006", 
     "created_at": "2012-10-29T14:01:56Z", 
     "owner": { 
      "_id": "508c06e4bcd7ac4108000009", 
      "name": "Client 1" 
     }, 
     "title": "2nd Try", 
     "updated_at": "2012-10-29T14:01:56Z", 
    }- 
] 

人有一個想法? 我想測試有點像to_hash方法,但它不工作...

回答

1

由於您使用ClientLocalisedFile之間的關係引用,客戶端的數據不會只複製的文件對象中, owner_id,使關係起作用。您需要通過您在LocalisedFile型號上定義的owner關係訪問客戶數據。例如:

l = LocalisedFile.first 
l.owner.id # returns the id of the owner 
l.owner.name # returns the name of the owner 

要創建你需要,我建議這個抽象成一個實例方法與類似的輸出類型:

class LocalisedFile 
    def as_hash_with_owner 
    hash = self.to_hash 
    hash[:owner] = { _id: self.owner.id, name: self.owner.name } 
    hash.except[:owner_id] 
    end 
end 

然後,你可以這樣做:

files = LocalisedFile.all.entries # or whatever criteria 
files.map { |f| f.as_hash_with_owner } 

這應該給你一個紅寶石數組哈希,然後你可以轉換爲JSON或任何你需要的格式。

+0

非常感謝您的回答,除了在Mongoid上下文中,模型#to_hash方法不存在。但用#as_document方法,它似乎工作。 因此,當我在模型中調試散列(在#as_hash_with_owner方法內)時,它很好。 但我該怎麼回報它? 因爲結果在控制器中沒有改變... files = LocalisedFile.all files.map {| f | f.as_hash_with_owner} logger.debug「Files:#{files}」 respond_to do | format | \t format.json {渲染:JSON => files.to_json,:狀態=>:OK】 結束 似乎並不工作... –

+0

#to_hash應該叫上的文檔,而不是一個標準或模型類。我也使用Mongoid 3.0.9,不知道這是否可能不存在於舊版本。 #to_json也可以正常工作。看起來問題在你的控制器中。 – Vickash

+0

第二個想法是,如果你要做很多這個,你應該看看jbuilder:https://github.com/rails/jbuilder – Vickash