0

この質問はすでに何百万回も尋ねられているに違いありませんが、私は答えを見つけることができませんでした:(

3つのモデルがあると仮定します:

class Country
  has_many :cities
end

class City
  has_many :companies
end

class Company
  belongs_to :city
end

指定された City の会社を で取得できますCity.first.companiesが、私が望むのは、指定された Country のすべての会社を取得できるようにすることです。Country.first.companies

私が達成できたのは、Countryモデルにメソッドを書くことです:

 def companies
   @companies = []
   cities.all.each{ |c| @companies << c.companies unless c.companies.empty? }
   @companies
 end

ただし、それは Company オブジェクトの配列の配列を返します。country_id次のように、Country モデルの FK として列を追加することもできました。

class Country
  has_many :cities
  has_many :companies
end

class Company
  belongs_to :city
  belongs_to :country
end

しかし、それはあまりDRYに見えません。

特定の国の Company オブジェクトの配列を受け取りたいです。これを実現するRailsの方法があると確信しています。それはどうなりますか?

ありがとう!

4

1 に答える 1

1

has_many through協会 をご利用ください。

class Country
  has_many :companies, :through => :cities

を使用できるようになりCountry.last.companiesました。

于 2012-11-13T12:37:29.760 に答える