Search code examples
ruby-on-railsurlhelper

what is the right 'rails' way to add a link_to a new custom method


We're adding a new method 'delete_stuff' to the WidgetsController of a scaffolded app.

in routes we added match 'widget/delete_stuff/:id' => 'widgets#delete_stuff'

I CAN manually create html (GET) links like

<a href="/widget/delete_stuff/<% widget.id %>">My Custom Delete Stuff</a>

But that's bad on so many levels (uses GET instead of DELETE, doesn't permit a CONFIRM dialog, isnt DRY, etc)

Problem is I can't figure out how to use the url helpers for a custom method... trying to do something like this:

<% link_to 'DeleteStuff', @widget, :confirm => 'Are you sure?', :method => :delete %>

But that just gets ignored when the html is rendered.

I'm clearly missing something fundamental on how to use link_to, any help will be appreciated!

Cheers, JP


Solution

  • First run rake routes to know what URL helpers are available to you. You may see a line beginning with:

    delete_stuff_widget
    

    You can then append path or url to get the name you should use in your views and controllers. I suspect your new link_to will look like:

    link_to  "DeleteStuff", delete_stuff_widget_path(@widget), :confirm => "Sure?", :method => :delete