【发布时间】:2011-12-09 09:25:36
【问题描述】:
ActiveResource::Base#update_attributes 方法调用ActiveResource::Base#load 方法,该方法在activeresource-3.1.3/lib/active_resource/base.rb(第 1255 行)中定义。我试图调用 load 方法,而不是简单地使用 update_attributes 以便不会立即保存对象。
-
我使用全新的 Rails 应用程序对此进行了测试。我搭建了一个简单的对象:
rails scaffold obj property1:string -
然后在 Rails 控制台中:
irb(main):001:0> obj=Obj.new irb(main):002:0> obj.load(:property1=>"data") TypeError: can't convert Hash into String from .../activesupport-3.1.3/lib/active_support/dependencies.rb:234:in `load' from .../activesupport-3.1.3/lib/active_support/dependencies.rb:234:in `load' from .../activesupport-3.1.3/lib/active_support/dependencies.rb:223:in `load_dependency' from .../activesupport-3.1.3/lib/active_support/dependencies.rb:640:in `new_constants_in' from .../activesupport-3.1.3/lib/active_support/dependencies.rb:223:in `load_dependency' from .../activesupport-3.1.3/lib/active_support/dependencies.rb:234:in `load' from (irb):2
我看到activesupport-3.1.3/lib/active_support/dependencies.rb 将其Loadable 模块应用于Object,为每个对象提供了一个load 方法来加载文件,但我不明白为什么它会覆盖ActiveResource::Base#load 方法而不是反过来。
我正在使用 Rails 3.1.3 和朋友。
更新:
我想我已经回答了我自己的问题。我一直在尝试对 ActiveRecord 对象使用 ActiveResource 方法。我知道我的 Rails 模型类是 ActiveRecord::Base 的后代,但不知何故,当我试图找到 ActiveRecord::Base#update_attributes 的代码时,我找到了 ActiveResource::Base#update_attributes 的代码,看起来像这样:
def update_attributes(attributes)
load(attributes, false) && save
end
所以我一直在尝试调用load 方法,该方法仅适用于我的对象,仅由activesupport 提供。如果我只看ActiveRecord::Base#update_attributes 这是
def update_attributes(attributes, options = {})
# The following transaction covers any possible database side-effects of the
# attributes assignment. For example, setting the IDs of a child collection.
with_transaction_returning_status do
self.assign_attributes(attributes, options)
save
end
end
我会看到assign_attributes 方法是我所需要的。
【问题讨论】:
标签: ruby-on-rails