【问题标题】:Is it possible to call ActiveResource::Base#load?是否可以调用 ActiveResource::Base#load?
【发布时间】: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 以便不会立即保存对象。

  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 方法是我所需要的。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

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

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

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

    阅读Docs了解更多信息。

    【讨论】:

    • 谢谢,这适用于我上面的测试用例,但我需要一些最终能够处理复杂数据的东西,比如嵌套参数。
    • 经过进一步检查,我发现obj.assign_attributesobj.attributes= 实际上在 Rails 3.1.3 中处理嵌套参数的方式相同。现在唯一的区别(Rails 3.2.1)与安全角色有关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    相关资源
    最近更新 更多