将依赖字段添加到Mongoid的输出中

时间:2016-03-31 15:21:15

标签: 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

class Country
  include Mongoid::Document

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

  has_many :cities
end

在控制器中我使用

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

接收城市名单。

以下是每个城市的JSON输出:

...

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

...

如何获得country代替country_id

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

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

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