我有幾個模型是多個對象的組合。我基本上手動管理他們的保存和更新。但是,當我選擇項目時,我無法訪問所述項目的關聯屬性。例如:在模型對象的什麼級別ActiveRecord不加載關聯的對象
class ObjectConnection < ActiveRecord::Base
def self.get_three_by_location_id location_id
l=ObjectConnection.find_all_by_location_id(location_id).first(3)
r=[]
l.each_with_index do |value, key|
value[:engine_item]=Item.find(value.engine_id)
value[:chassis_item]=Item.find(value.chassis_id)
r << value
end
return r
end
end
和每個項目:
class Item < ActiveRecord::Base
has_many :assets, :as => :assetable, :dependent => :destroy
當我使用ObjectLocation.find_three_by_location_id,我沒有獲得資產,而如果使用Item.find(ID)在大多數其他情況, 我做。
我嘗試過使用includes,但似乎沒有這樣做。
THX
我試過了,但引擎和底盤都是'項目',我不能'belongs_to:item,:foreign_key =>'engine_id',belongs_to:item,:foreign_key =>'chassis_id''。看起來這種關係似乎是一個'has_one',但老實說,如何建立這個模型已經超出了我的視野。發動機和底盤不是多形的。現在,is_engine有is_chassis的狀態字段。這部分肯定有點難看,但它的建模方式在應用程序的其他部分工作得很好。 – timpone 2012-03-09 20:51:11
對我來說,聽起來像你最好把'Item'作爲超類,然後製作一個獨立的'Engine'和'Chassis'模型,它們是Item的子類。然後爲你的'Item'類指定一個'polymorphic'關係(這將會逐漸下移到其他類)。 [在這裏閱讀更多關於ActiveRecord多態關係](http://guides.rubyonrails.org/association_basics.html#polymorphic-associations)。如果你真的想堅持你目前的設置(我不會推薦),那麼請閱讀我修改後的答案的底部。 – Batkins 2012-03-09 20:57:43
您提到的那部分代碼工作正常 - 在視圖中輸出正確的數據。 – timpone 2012-03-09 21:02:58