Wednesday, February 13, 2008

ActiveResource < ActiveRecord

I'll save you some time: ActiveResource is not a drop-in replacement for ActiveRecord. Perhaps you knew that, but I did not, and wasted half a day because of it. It looks similar, and acts similar - but don't be fooled. It will not work with any plugin that is built to work for active record (to be expected) or many plugins built to work with controllers (color me surprised), like make_resourceful or resource_this.

So, here is a list of things active resource is missing:

update_attributes

Causes update on generated scaffolds and controller plugins to break

associations

Associations are sweet methods like has_many or belongs_to. Without them, it is impossible to map any sort of ActiveResource hierarchy - so just accept that there is none.

field mapping

Should come as no surprise, but active resource cannot give you any information about the underlying REST-populated structure until AFTER it has made the call. Similar to the painful lack of associations - you cannot even dissect the ARec object.

So don't get too excited about ActiveResource. It still needs a lot of work before the dream of pure REST-driven-object-based service/client separation can exist on the scale of simplicity of the ActiveRecord pattern. Until then - you still need to manually manage your resource objects (unless they are simple) - likely via the Controller.

Update: "update_attributes" doesn't exist. Something similar exists named "load". So:
mar = MyARes.find(:first)
mar.load({:my_val => "hi"})

2 comments:

kylejginavan said...

Thanks for the info. update_attibutes is a beautiful thing and wouldn't want to live life without it. Based on your findings Eric, what would be an appropriate application of ActiveResource rather than ActiveRecord?

Eric said...

ActiveResource is fine if all you want to do is abstract the communication between a REST server and your client server. It's a powerful feature, to be sure. It's just that despite the similarities between AR and ARec they are not compatible. Perhaps in the future this will change - but it kind of makes me lean toward standard web services for the moment - since the existence of a WSDL would allow an abstraction like ARec to match the features of AR.