Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 将相关字段添加到Mongoid';s输出_Ruby On Rails_Ruby_Mongoid - Fatal编程技术网

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