Is it possible to call ActiveResource :: Base # load?

The ActiveResource::Base#update_attributes method calls the ActiveResource::Base#load method, which is defined in activeresource-3.1.3/lib/active_resource/base.rb (line 1255). I am trying to call this method load , and not just use update_attributes so that the object is not saved immediately.

  • I tested this with a completely new rail application. I ran a simple object:

     rails scaffold obj property1:string 
  • Then in the rails console:

     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 

I see that activesupport-3.1.3/lib/active_support/dependencies.rb applies its Loadable module to Object , providing each object with a load method to load files, but I cannot understand why it overrides the ActiveResource::Base#load method, not in another way.

I am using Rails 3.1.3 and friends.

Update:

I think I answered my question. I am trying to use ActiveResource methods for ActiveRecord objects. I know that my Rails model classes are descendants of ActiveRecord::Base , but for some reason, when I tried to find the code for ActiveRecord::Base#update_attributes , instead I found code for ActiveResource::Base#update_attributes , which looks like this :

 def update_attributes(attributes) load(attributes, false) && save end 

So, I tried to call the load method, which exists for my objects only in the form in which activesupport provides it. If I only looked at ActiveRecord::Base#update_attributes , which

 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 

I would see that the assign_attributes method is what I need.

0
source share
1 answer

You can use .attributes instead

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

The instance has new attributes but has not been saved.

Read more Documents .

0
source

Source: https://habr.com/ru/post/1369383/


All Articles