RESTful routes and adding/removing associations

Hi,
I’m trying to make a restful route to Add and Remove relationships
between a Contact and a Customer.

I have a Contact and a Customer model that looks like
def Contact < ActiveRecord::Base
has_many :customer_mappings, :class_name =>
“ContactMapping”, :foreign_key => “contact_id”
has_many :customers, :through => :customer_mappings

end

Customer model looks similar but with has_many :contacts… instead.

In my contacts and customers controller I have methods to add and
remove a contact/customer, like this (very simplified):
ContactsController#add_customer
Contact.find(params[:id]).customer_mappings <<
ContactMapping.new(:customer => Customer.find(params[:customer_id])
end

Now, what is the best way to accomplish a named route for this in Rest-
style ?
I already have the map.resources :contacts in routes.rb.

What I’d like is an add_customer_contact_url (or similar) method so I
could do something like

form_remote_tag(:url => add_customer_contact_url(@contact), :method
=> :post) and then just pass along the customer_id.

I’ve tried various settings in routes.rb but I can’t seem to get it
right.

Can anyone help?

When i put this in routes.rb
map.resources :contacts, :member => { :add_customer
=> :post, :remove_customer => :delete }

the add_customer_contact_url(@contact) is working as expected.

But the route for remove_customer_contact_url doesn’t work, or it
“works” but not as expected.

‘rake routes’ says:
remove_customer_contact DELETE /contacts/:id/remove_customer
{:action=>“remove_customer”, :controller=>“contacts”}

But i expected an URL like /contacts/:id/remove_customer/:customer_id

Any ideas?

Ok, I had to buy the REST for Rails 2 screencast from PeepCode
https://peepcode.com/products/rest-for-rails-2, and after watching
it for 5minutes I got the answer :slight_smile:

In routes.rb i have:
map.resources :contacts, :member => { :add_customer
=> :post, :remove_customer => :delete }

and in my view I can now call
<%= link_to “Remove”,
remove_customer_contact_url(@contact, :customer_id =>
customer_id), :method => :delete %>

Well worth $9 :slight_smile: