views:

103

answers:

2

Using a restful resource in Rails, I would like to be able to insert a link into my flash hash that the user can click to destroy the object in question. The only problem seems to be that I cannot get the generated link to work with the RESTful controller!

First I tried

link_to "Change your reservation", reservation_path(@existing_reservation), :method => :delete

This didn't work because link_to is a helper method in ActionView, not available in controllers

Next find was url_for

url_for :controller => 'reservations', :actions => 'destroy', :method => :delete

which took me back to the show action. I have tried every combination of the two that I can find . . . but I can't seem to create a link in my controller that will slip in the delete method! Every action I generate produces a normal link (GET), which calls the show method.

Any ideas?

A: 

Instead of using a path, try passing just the object itself, e.g.

link_to "Change your reservation", @existing_reservation, :method => :delete
Schrockwell
Can't use the "link_to" method in controllers . . . its only for the views.
BushyMark
Yeah, you're right. Sorry, I didn't read your message closely enough. Short of hard-coding the link into the view, I'm pretty stumped on this one.
Schrockwell
+1  A: 

ApplicationController.helpers.link_to will allow you to use helper methods in the controllers, although I'm not sure that's strictly following MVC. Although occasionally I've found a need, i.e. calling number_to_currency.

Another problem arises when you use the :delete option in that particular helper. It will fail. After a quick glance at the source code I cant really see an immediate fix.

Firstly, I would recommend you put the delete link somewhere else on that page if possible. If you really need it in the flash you could modify the flash in the view.

I.e. in the controller setup the flash:

flash[:notice] = "Flash message with a  DELETE LINK in it"

Then in the view modify that flash before displaying it:

<%=  flash[:notice].gsub(/DELETE LINK/, link_to("delete", resource_path, :method => :delete)) %>

You would probably want to just make that into your own helper. If you don't like gsub-ing the text like that I'm sure you could find another way, how about just appending the link to the flash?

Hope that helps : )

tsdbrown
Love it! thanks!
BushyMark