views:

844

answers:

1

I have a Rails application that has a Company resource with a nested resource Employee. I'm using shallow routing, so to manipulate Employee, my routes are:

GET     /employees/1
PUT     /employees/1
DELETE  /employees/1
POST    /companies/1/employees

How can I create, read, update, and destroy Employees using ActiveResource?

To create employees, I can use:

class Employee < ActiveResource::Base
  self.site = "http://example.com/companies/:company_id"
end

But if I try to do:

e=Employee.find(1, :params => {:company_id => 1})

I get a 404 because the route /companies/:company_id/employees/:id is not defined when shallow routes are used.

To read, edit, and delete employees, I can use:

class Employee < ActiveResource::Base
  self.site = "http://example.com"
end

But then there doesn't seem to be a way to create new Employees, due to the lack of the companies outer route.

One solution would be to define separate CompanyEmployee and Employee classes, but this seems overly complex.

How can I use a single Employee class in ActiveResource to perform all four CRUD operations?

+2  A: 

There is a protected instance method named collection_path that you could override.

class Employee < ActiveResource::Base
  self.site = "http://example.com"

  def collection_path(options = nil)
    "/companies/#{prefix_options[:company_id]}/#{self.class.collection_name}"
  end
end

You would then be able to this to create employees.

e = Employee.new(:name => "Corey")
e.prefix_options[:company_id] = 1
e.save

It doesn't seem like the prefix_options is documented other than in the clone method so this might change in future releases.

Corey
Worked great, except I needed to use "/companies/#{prefix_options[:company_id]}/#{self.class.collection_name},xml" or the POST wasn't interpreted as XML.
Rich Apodaca