2009-08-21 5 views
1

はbetween..Hereの抽象化で別の使用して2つの仲介のモデルに一つのモデルに参加している:私はCountry.firstを行うことができるようにしたい2つのモデル間に複数のモデルを持つhas_many関係を作成するにはどうすればよいですか? (RailsのActiveRecordの上のルビー)私が何をしたいのですがどのような

 
Country has_many Companies 
Company has_many Buildings, Company belongs_to Country 
Building has_many Rooms, Building belongs_to Company 
Room belongs_to Building 

rooms .building_id = building .ID WHERE((ON buildingsを登録しようrooms INNER FROM SELECT *:しかし、これはのようなSQLを生成しようと

 
class Country - ActiveRecord::Base 
    has_many :companies 
    has_many :buildings, :through=>:companies 
    has_many :rooms, :through=>:buildings 
end 

:.roomsので、私は国のモデルはのような単純なものだろうと思いましたbuilding .country_id = 1))

明らかに、building.country_idは存在しません...どうすればこの問題を回避できますか?

+0

Rails(具体的にはActiveRecord)のバージョンは何ですか? – steel

答えて

1

組み込みの関連メソッドはここでは役に立ちません。あなたが使用して明示的にクエリを構築する必要がありジョイン:

class Country - ActiveRecord::Base 

    has_many :companies 
    has_many :buildings, :through=>:companies 

    def rooms 
     Room.all :joins => { :building => { :company => :country } }, :conditions => { "countries.id" => id } 
    end 

end 

これは

+0

これで、エラーメッセージが表示されます。 ActiveRecord :: ConfigurationError: 'country'という名前のアソシエーションが見つかりませんでした。おそらくあなたはそれを間違って綴ったでしょうか? 国から削除された1つのモデル(国に明示的に属している「会社」によって関連付けられている)である「建物」は、国に暗黙的に関連しているだけなので、推測しています。 –

+0

あなたは私がそれを逃した – derfred

0

これはRailsの3.1の後に可能である使用してみてください建物の上に設定するbelongs_toの団体や会社のモデルが必要になります。以下のコードは私のために働く。各レベルでhas_manyを指定することが重要です。

class Country 
    has_many :companies 
    has_many :buildings, through: :companies 
    has_many :rooms, through: buildings 
end 

class Company 
    has_many :buildings 
end 

class Building 
    has_many :rooms 
end 

class Room 
end 
関連する問題