I am using mongoid 3 in a rails 3 application.
I have a client class with referenced object ‘files’ (so instances of a custom ‘LocalisedFile’ class.)
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
No problem to manage my documents.
But when I want to render an array of files, I just get a “owner_id” field with the client string 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",
}-
]
That’s maybe normal, but I would like to get the clients informations, to use it in a JS application with Google Maps API, like this :
[(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",
}-
]
Anyone have an idea ?
I would like to test something like the to_hash method but it does not work…
Since you’re using a referenced relation between
ClientandLocalisedFile, the client’s data does not get replicated inside the file objects, only theowner_id, to make the relation work. You need to access the client data through theownerrelation you defined on theLocalisedFilemodel. For example:To create the kind of output you need, I’d suggest abstracting this into an instance method with something like:
Then you can do something like:
This should give you a ruby array of hashes which you can then convert to JSON or whatever format you need.