1

クラス:

class RefCountry < ActiveRecord::Base
  has_many :cities, :class_name => :RefCity, :foreign_key => "country_id", :primary_key => "country_id"
end

class RefCity < ActiveRecord::Base
  belongs_to :country, :class_name => :RefCountry, :primary_key => "country_id"
end

すべてのリンクが機能しています。

やろうとしたら

RefCity.joins(:country)

私は ActiveRecord::Relation を取得します

[
RefCity country_id: 1306, region_id: 4515, city_id: 67101, name_en: "Ust-Orda">, 

RefCity country_id: 1285, region_id: 4483, city_id: 67102, name_en: "Ust-Tarka", ...]

しかし、私はデータ型を取得したいだけです

{city_id1, city_name1, country_id1, country_name1},
{city_id2, city_name2, country_id2, country_name2},
...
{city_idN, city_nameN, country_idN, country_name}

ajaxで使用するため

4

1 に答える 1

1

これを試してみてください

 >> cities = RefCity.joins(:country).select('ref_cities.id, ref_cities.name, ref_cities.country_id, countries.name AS country_name')
 >> cities.first.id # city id
 >> cities.first.name # city name
 >> cities.first.country_id # country id
 >> cities.first.country_name # country name
 >> cities.map { |city| [city.id, city.name, city.country_id, city.country_name] }
于 2013-01-31T12:36:05.287 に答える