I have a partial for a "guest" object which renders a link to a destroy action like this:
<%= link_to_remote "remove", :url => { :action => "destroy", :id => guest.id } %>
When called from an ERB view it works fine, e.g.
<div id="guests">
<%= render :partial => @event.guests %>
That is, it renders something like:
<a href="#" onclick="new Ajax.Request('/guests/destroy/10', {[options removed]}); return false;">remove</a>
The problem is, when this partial is rendered from RJS as a result of a create operation like this:
page.insert_html :bottom, :guests, :partial => @guest
Instead of linking to the destroy action, it links to the detail/show action for the guest instead, e.g.
a href="#" onclick="new Ajax.Request('/events/1/guests/10', {[options removed]}); return false;">remove</a>
Can anyone tell me what I'm doing wrong, or if there's a way to debug what's going on here? As you might be able to tell, I'm a complete newbie to Rails ;)
You were doing it almost right, but you're not quite following convention. Allow me to explain.
Links are designed, by HTTP specification, to be GET requests - data retrieval. You are not supposed to use links to modify a resource's state. Basically, don't use links for potentially destructive actions, as they could be followed by a spider or accelerator. Rails defaults to making every link a GET request. So, when you did this:
<%= link_to_remote "remove", :url => { :action => "destroy", :id => guest.id } %>
It made a GET request. I assume you have in your routes.rb file something like
map.resources :guests
This creates a ton of routes that you could use like this:
<%= link_to_remote "remove", :url => guest_path(guest) %>
With resource routes in Rails, the METHOD used determines the controller action called.
The URL /guests/1 called with a GET request calls the SHOW action. You need to specify the method in your link_to_remote call - either :get, :put, :post, or :delete. :put is for updates, :post is for creates, :delete is for, well, deleting.
<%= link_to_remote "remove", :url => { :action => "destroy", :id => guest.id }, :method => :delete %>
or cleaner,
<%= link_to_remote "remove", :url => guest_path(guest), :method => :destroy %>
But seriously, don't use links. Use buttons.
<%= button_to_remote "remove", :url => guest_path(guest), :method => :destroy %>
Hope that helps!