2012-06-03 26 views
1

比方說,我有如下建模的Rails應用程序:找到所有物品通過兩個has_many關聯

  1. 有一間房子類;它has_many房間
  2. 有一個ROOM類;它屬於一個HOUSE和has_many傢俱
  3. 有一個FURNISHING類;它屬於一個房間

給這個模型設置,如何找到一個給定的房屋所有的傢俱?我希望能夠做到像arbitrary_house.furnishings這樣的事情。

這是可能的,但不添加更多的關聯?

回答

1

設置你的模型如下:

house.rb

has_many :rooms 
has_many :furnishings, :through => :rooms 

room.rb

belongs_to :house 
has_many :furnishings 

furnishing.rb

belongs_to :room 

現在你可以說

arbitrary_house.furnishings 

另見:

http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association 
+0

我覺得愚蠢...現在如果只Mongoid支持:通過 – aren55555

+0

的Rails和Ruby能做到這一點。我花了兩天時間,直到找到資本。我的預堆棧溢出日。 – Anil

+0

由於mongoid不支持:通過,我不得不做HOUSE,has_many傢俱和傢俱belongs_to HOUSE – aren55555

相關問題