是否可以调用ActiveResource :: Base#load?

ActiveResource::Base#update_attributes方法调用ActiveResource::Base#load方法,该方法在activeresource-3.1.3/lib/active_resource/base.rb (第1255行)中定义。 我试图调用该load方法,而不是简单地使用update_attributes以便不立即保存该对象。

  1. 我用一个全新的rails应用程序测试了它。 我搭建了一个简单的对象:

     rails scaffold obj property1:string 
  2. 然后在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方法是我需要的。

您可以使用.attributes而不是这样做

 obj = Obj.new obj.attributes = { :property1 => "data" } 

该实例具有新属性,但尚未保存。

阅读文档了解更多信息。