Rails: ActiveResource - can I set the identifier explicitly?

I am using ActiveResource in Rails to manage objects in a separate database through REST.

I am trying to explicitly manage the identifiers of the remote resources, since for the current case it’s easier to just reuse the identifier of the local resource and not support another field.

Unfortunately, I was not able to get this to work, since the code is new? in ActiveResource::Base there is

  def new? id.nil? end 

and save is

  def save new? ? create : update end 

So, from this, by definition, it is impossible to set the resource identifier and save it as a new resource.

create and update are protected methods, so if I hacked ActiveResource :: Base, maybe that would make it work, but I don't want to.

Is there a proper way to do this? Or is it what I'm trying to do is just bad, and I should not do this?

+6
rest ruby-on-rails activeresource
source share
2 answers

You work against ActiveResource intentions. ActiveResource provides an interface for REST web services, which by convention return the assigned identifier when you create.

However, if you control the resource you are using and you change its behavior to take an identifier when saving a new record, you can change ActiveResource :: Base to match. In Rails, additions and changes to base classes are very rare; you just put your patch in lib and include it somewhere in your stuff to run.

I do not think this is a good idea, certainly, but it is possible. :)

+2
source share

On new rails (checked 2.3.2), an id can be set, since the save logic has changed a bit (now records have a @newrecord logical field to exclude this id.nil?).

 record = Model.new record.id = 123 record.save! 
+4
source share

All Articles