2016-03-31 3 views
0

Ich habe zwei Modelle:In dem Mongoid des Ausgangs abhängiges Feld

class City 
    include Mongoid::Document 

    field :alternate_names, type: String 
    field :coordinates, type: Array 
    field :name, type: String 

    index({ coordinates: '2d' }, { min: -180, max: 180 }) 

    belongs_to :country 
end 

und

class Country 
    include Mongoid::Document 

    field :iso_3166_code, type: String 
    field :name, type: String 

    has_many :cities 
end 

In der Steuerung I

@cities = City.where(alternate_names: /#{params[:query].downcase}/).limit(10)

in Städte-Liste erhalten verwenden.

Hier ist ein JSON-Ausgang für jede Stadt:

... 

"country_id": { 
    "$oid": "56fc453eae3bbe5c2abcd933" 
} 

... 

Wie kann ich country bekommen statt es ist country_id?

+0

Warum können Sie nicht 'countries = @ cities.map (&: country)'? – Anthony

+0

Es gibt nur Länder zurück, aber ich brauche ein vollständiges Stadtobjekt mit eingebetteten Ländern. – kleverigheid

+0

Mongoid wird das für Sie tun, wenn Sie also durch Ihre 'Städte' gehen, wird jede' Stadt' 'Land' haben ... – Anthony

Antwort

0

Ich fand eine Lösung.

@cities = City.where(alternate_names: /#{params[:query].downcase}/).includes(:country).limit(10) 

render json: @cities, except: :country_id, include: :country 
Verwandte Themen