0

Rails 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

LocalizedFile.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",
    }-
]

誰にもアイデアがありますか?to_hash メソッドのようなものをテストしたいのですが、うまくいきません...

4

1 に答える 1

1

Clientと の間で参照関係を使用しているためLocalisedFile、クライアントのデータはファイル オブジェクト内では複製されず、 のみが複製されowner_id、関係が機能します。モデルownerで定義したリレーションを介してクライアント データにアクセスする必要があります。LocalisedFile例えば:

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 }

これにより、ハッシュの ruby​​ 配列が得られ、JSON または必要な形式に変換できます。

于 2012-10-30T03:23:55.103 に答える