2012-05-14 107 views
0

模型關聯是如下:未定義的方法爲#`更新」 <ActiveRecord的::協會:: HasOneAssociation

模型I

class TimeLog < ActiveRecord::Base 
    has_one :custom_time_field, :dependent => :destroy 
end 

模型II

class CustomTimeField < ActiveRecord::Base 
belongs_to :time_log 
end 

錯誤詳細信息:

a = TimeLog.find(1) 
a.custom_time_field 

#returns => #<CustomTimeField id: 1, time_entry_id: 1, status: 'incomplete', start_time: "2000-01-01 11:24:00", end_time: "2000-01-01 11:24:00"> 

a.custom_time_field.update(1, :status => '') # returns undefined method `update' 

然而a.custom_time_field.update_attributes()的作品

現在我可以通過創建對象

使用同樣的update_attributes我可以用節省的方法,但爲什麼不能我使用更新方法在這種情況下?當需要一次更新多個屬性時,這很有用。

評論/指針?

+0

我意識到更新方法適用於類而不是對象。但那我怎麼能用class來調用它與一個關聯? –

+0

有些困惑:你的CustomTimeFields類最後需要''嗎?日誌顯示它的名字沒有's'。 – jdoe

+0

哦,是的。 thnx引起注意。 –

回答

2

update是您的模型的類方法。這樣稱呼:

CustomTimeField.update(1, :status => '') 
+0

我希望我可以使用它。但是我在運行時有TimeLog的ID。 thnx暗示雖然 –

+1

我剛剛告訴你,'更新'是在你知道id時使用的。如果你已經有了你的模型的實例,那麼'record.update_attributes'就非常適合。 – jdoe

相關問題