views:

374

answers:

3

I've got a page where I'm dynamically adding elements to a from a series of select boxes. I'm using RJS to do this and it's working great. Now, these elements in the div are a series of that are accompanied by Delete buttons, in case the user wants to remove a textarea. Here's where I'm hitting a wall.

Here's the code that runs the Delete button. This is working well to my knowledge:

<%= link_to image_tag("/images/button_delete.gif", :alt=>"Delete"), :controller=>"report", :action=>"remove", :id=>@sentence.id %>

In my report controller, I've got this very simple method being called by the above code:

def remove @sentence_id = params[:id] end

Again, I think that's working. Now, when I activate this action by hitting the button, off we go to the RJS file, remove.rjs:

page.remove 'sentence_'+@sentence_id

And here's what I get in my browser, instead of a happily removed element!

try 
{
     Element.remove("sentence_63");
} 
catch (e) 
{ 
     alert('RJS error:\n\n' + e.toString()); 
     alert('Element.remove(\"sentence_63\");'); 
     throw e; 
}

My understanding is that this happens when there's no page in the current context. Online documentation on this is kind of thin.

Any help appreciated! Cheers, Aaron.

+1  A: 

Try link to remote. That will build the ajax call for you and should remove the element from the page.

Then link_to_remote syntax is slightly different than the link_to syntax, so don't let that trip you up either.

PJ Davis
A: 

Your Delete link is setup as a normal link, i.e.

<a href="/report/remove" id="sentence_63">
  <img src="/images/button_delete.gif" alt="Delete" />
</a>

which triggers a normal HTTP request. Since your intent is to trigger an AJAX request, try PJ Davis' recommendation and use link_to_remote

John Douthat
A: 

Since your remove function doesn't seem to actually delete a record, if you just want to remove an HTML element from a page you can use link_to_function with the Prototype remove() method for Elements. In addition, if you've got a recent version of Rails (for example, 2.3.2) you can take advantage of the dom_id helper to auto generate the sentance_id ID attribute

<%= link_to_function(image_tag("button_delete.gif", :alt=>"Delete"), "$('#{dom_id(@sentence}').remove();" %>

An approach like this could help keep the number of methods down in your controller (unless you intend on doing something else in the controller)

Scott