After reading the book RESTful Web Services by Leonard Richardson and Sam Ruby, it seems to me, that the to_xml method of rails is not as restful as it should be. Specifically, the book introduces the Resource Oriented Architecture, one of the tenets of which is connectedness: Representations of a resource should contain not only the data of the resource, but also links to other resources.
However, when rails scaffolds a resource, it implements requests for a xml representation by deferring to [model]#to_xml. This method does not have access to the normal path helpers, so any links to other resources are only indicated by their ids, not by their uris.
I have solved this problem for now, but the solution doesn't seem very robust: Given a Employer resource with nested Employees, the following code (sort of) adds uris to their xml serialization:
class Employee < ActiveRecord::Base
include ActionController::UrlWriter
belongs_to :employer
def to_xml(options = {})
options[:procs] = [ Proc.new {|options| options[:builder].tag!('uri', employer_employee_path(employer, self)) } ]
if options[:depth].nil?
options[:depth] = 1
end
if options[:depth] != 0
options[:depth] -= 1;
options[:include] = [:employer]
end
super(options)
end
end
class Employer < ActiveRecord::Base
include ActionController::UrlWriter
has_many :employees
def to_xml(options = {})
options[:procs] = [ Proc.new {|options| options[:builder].tag!('uri', employer_path(self)) } ]
if options[:depth].nil?
options[:depth] = 1
end
if options[:depth] != 0
options[:depth] -= 1;
options[:include] = [:employees]
end
super(options)
end
end
The UrlWriter allows me to properly create the path of a resource (not the full uri, though. The domain will have to be pasted on to the path by the clients of my web service). Now the models are responsible for their own uri, and for including the representation of any connected resource. I use the :depth option to avoid recursing endlessly.
This method works, but as stated before, it doesn't seem quite right, with all the duplication. Has anybody else had the same problem and does anybody else have a better idea of how to get uris in the xml representation?