2012-03-09 20 views
0

我有幾個模型是多個對象的組合。我基本上手動管理他們的保存和更新。但是,當我選擇項目時,我無法訪問所述項目的關聯屬性。例如:在模型對象的什麼級別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

回答

1

聽起來像最簡單的解決辦法是將方法添加到您的ObjectConnection型號爲方便,像這樣:

class ObjectConnection < ActiveRecord::Base 

    def engine 
    Engine.find(engine_id) 
    end 

    def chassis 
    Chassis.find(chassis_id) 
    end 

    # rest of class omitted... 

我不完全知道你是問什麼?如果這不能回答你所問的問題,那麼你是否可以試着更清楚自己想要達到的目標? ChassisEngine mdoels是否與您的Item模型有多態關係?

此外,上面使用的代碼將不起作用,因爲您試圖在模型上動態設置屬性。這不是您打給Item.find的呼叫失敗,而是您撥打value[:engine_item]=value[:chassis_item]失敗的呼叫。您將需要修改它是這樣的,如果你想保持這種流動:

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 |obj_conn, key| 
    # at this point, obj_conn is an ActiveRecord object class, you can't dynamically set attributes on it at this point 
    value = obj_conn.attributes # returns the attributes of the ObjectConnection as a hash where you can then add additional key/value pairs like on the next 2 lines 
    value[:engine_item]=Item.find(value.engine_id) 
    value[:chassis_item]=Item.find(value.chassis_id) 
    r << value 
    end 
    r 
end 

但我仍然認爲,這整個方法似乎沒有必要因爲這樣的事實,如果你設置你的ObjectConnection模型正確關聯首先,你不需要去嘗試手動處理關聯,就像你在這裏試圖做的那樣。

+0

我試過了,但引擎和底盤都是'項目',我不能'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

+0

對我來說,聽起來像你最好把'Item'作爲超類,然後製作一個獨立的'Engine'和'Chassis'模型,它們是Item的子類。然後爲你的'Item'類指定一個'polymorphic'關係(這將會逐漸下移到其他類)。 [在這裏閱讀更多關於ActiveRecord多態關係](http://guides.rubyonrails.org/association_basics.html#polymorphic-associations)。如果你真的想堅持你目前的設置(我不會推薦),那麼請閱讀我修改後的答案的底部。 – Batkins 2012-03-09 20:57:43

+0

您提到的那部分代碼工作正常 - 在視圖中輸出正確的數據。 – timpone 2012-03-09 21:02:58

相關問題