2012-10-29 2 views
0

레일 3 애플리케이션에서 mongoid 3를 사용하고 있습니다.몽고이드 렌더링 된 완전한 객체

내가 참조 된 개체 '파일'과 클라이언트 클래스가 (사용자 정의 '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", 
    }- 
] 

,하지만 난 클라이언트를 좀하고 싶습니다 정보를 Google Maps 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", 
    }- 
] 

누구나 아이디어가 있으십니까? 당신이 ClientLocalisedFile 사이의 참조 관계를 사용하고 있기 때문에 ...

답변

1

을 나는 to_hash 방법 같은 것을 테스트하고 싶지만 그것이 작동하지 않는 클라이언트의 데이터는 단지 파일 객체 내부에 복제되지 않습니다 owner_id, 관계 작업을 만들기 위해. LocalisedFile 모델에 정의한 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 

:

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

당신이, 내가 좋아하는 뭔가 인스턴스 방법으로이 문제를 추상화 좋을 것 필요한 출력의 종류를 만들려면

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