2012-08-22 29 views
0

我有這樣的事情:如何獲得我已擴展的關聯對象的ID?

class Person < ActiveRecord::Base 

has_many :things do 
     def [](kind) 
      find(:first, :conditions => ["kind = ?", kind.to_s]) 
     end 
    def []=(kind, config) 
     thing = self[kind] 

     if thing.nil? 
      #create new thing 
      ap self # prints all things that person has 
     else 
      # update 
     end 
    end 
end 

與上面的代碼,我可以這樣做person.things[:table],它會發現事情與任何人的身份證是和類型的表的爲person_id。第一種方法很好。

這是我不知道如何實現的第二種方法。 如果我想設置一個表的配置,我想這樣做person.things[:table] = {:my => "config"}

如果表已經存在,那將會很好。 但是如果我想創建一個新的thing

通常情況下,創造了事情是這樣的:

thing = Thing.new({ 
    person_id => person[:id], 
    kind => "table" 
    config => {} 
}) 

,但是,因爲我在做一個協會擴展,並希望創建一個新的對象,如何獲取人物ID?

使用
紅寶石1.8.7
軌2.3.14

回答

1

我最近沒有使用這個,但你有沒有試過

proxy_association.owner 

擴展裏面?我相信這應該會返回Person

文檔:RoR Guides

編輯:我剛剛注意到在你的例子中,Person不是一個ActiveRecord模型?那是遺漏嗎?

For Rails 2.3.14,你想用AssociationProxy'sproxy_owner方法。 然後只是做things.proxy_owner[:id]

+0

對不起,人是一個活躍的記錄模型。那麼.owner會返回人的實例嗎? – NullVoxPopuli

+0

是的,對於代理'proxy_association.owner.id'應該得到你的個人ID: thing = Thing.new({0}} {proxy_association.owner.id, kind =>「table」 config = > {} }) – niels

+0

我得到了'NoMethodError:未定義的方法'所有者'。我忘了提及我在使用ruby 1.8.7和rails 2.3.14。那很重要嗎? – NullVoxPopuli

相關問題