2012-05-14 42 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

相关问题