Ruby on rails 将相关字段添加到Mongoid';s输出
我有两种型号:Ruby on rails 将相关字段添加到Mongoid';s输出,ruby-on-rails,ruby,mongoid,Ruby On Rails,Ruby,Mongoid,我有两种型号: 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 及 在我使用的控制器中 @cit
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
及
在我使用的控制器中
@cities=City.where(备用名称:/{params[:query].downcase}/).limit(10)
接收城市列表
以下是每个城市的JSON输出:
...
"country_id": {
"$oid": "56fc453eae3bbe5c2abcd933"
}
...
如何获得country
而不是country\u id
?我找到了一个解决方案
@cities = City.where(alternate_names: /#{params[:query].downcase}/).includes(:country).limit(10)
render json: @cities, except: :country_id, include: :country
为什么不能执行
countries=@cities.map(&:country)
?它只返回国家,但是我需要嵌入国家/地区的完整城市对象。mongoid将为您这样做,因此当您遍历城市时,每个城市将具有国家/地区
。呈现json:@cities
返回每个城市的国家/地区id
,但我需要国家/地区
。
@cities = City.where(alternate_names: /#{params[:query].downcase}/).includes(:country).limit(10)
render json: @cities, except: :country_id, include: :country