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方法,但它不工作...
非常感謝您的回答,除了在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】 結束 似乎並不工作... –
#to_hash應該叫上的文檔,而不是一個標準或模型類。我也使用Mongoid 3.0.9,不知道這是否可能不存在於舊版本。 #to_json也可以正常工作。看起來問題在你的控制器中。 – Vickash
第二個想法是,如果你要做很多這個,你應該看看jbuilder:https://github.com/rails/jbuilder – Vickash