rod mclaughlin


How to add a Delete Confirmation Dialog in Merb (15 dec 08)

In Rails, adding a confirmation dialog ('Are you sure?') to a link which deletes something is easy:

<%= link_to 'delete', delete_user_path, :confirm => 'Are you sure?', 
:method => :delete %>


but in Merb, it's much harder...

david-burger.blogspot.com/2008/11/merb-javascript-delete-linkto-with.html

is the best explanation I could find...

It's written in Merb-speak:

'Just add a class to your link and then hook in your events with some prototype'

This means... write the following in eg. show.html.erb:

 <%= link_to 'Delete', url(:delete_article, @article), :class => 'delete-link' %>

and above that, somewhere,



<script type="text/javascript">
$(document).observe("dom:loaded", function(evt) {
    $$(".delete-link").invoke("observe", "click", function(evt) {
        evt.stop();
        if (confirm("Are you sure?")) {
            var href = evt.element().href;
            var href = href.substring(0, href.length - "/delete".length);
            var form = new Element("form", {action: href, method: "POST"});
            var _method = new Element("input",
                {type: "hidden", name: "_method", value: "DELETE"});
            form.appendChild(_method);
            $(document).body.appendChild(form);
            form.submit();
        }
    });
});
</script>


 

and create a destroy method in a controller

For example, my articles controller has

 def destroy(id)
    @article = Article.get(id)
    raise NotFound unless @article
    if @article.destroy
      redirect resource(:articles)
    else
      raise InternalServerError
    end
  end

 

Another example: in Merb it's

<%= text_area :body, :cols => "70", :rows => "30" %>

and in Rails it's

<%= f.text_area :message, {:size => "70x30"} %>

 



Back
Portland London