Vijay Dev
Vijay Dev

Reputation: 27476

Using HTML in Rails flash messages

I use flash[:error] to display a simple message to users that they cannot do a delete operation under certain conditions. I also have a link that will help them to get information about the entity that they wanted to delete and why they cannot do so.

Is it advisable to include this hyperlink in the flash message? Which would mean that I would have a HTML fragment in my controller. If not, how would I go about doing this?

Upvotes: 23

Views: 11235

Answers (3)

Ritchie
Ritchie

Reputation: 1506

If you want to include a link in your flash message from the controller there are 2 issues. Generating the link and then getting it displayed as HTML.

To use the link_to helper in the controller, fully qualify it.

To have the string display as html (instead of being escaped), call the html_safe method on the string. So the line in your controller might look like:

flash[:error] = "You can't do that. #{ActionController::Base.helpers.link_to "Here's why.", '/more_info.html'}".html_safe

Upvotes: 38

Nicolas Blanco
Nicolas Blanco

Reputation: 11299

the flash object is a holder for storing view fragments/messages and persist them for one redirection using the session. I see absolutely no problem in storing a link, or better an URL.

example :

redirect_to posts_path, :alert => "You cannot do that", :flash => { :url => post_path(@post) }

and in layout view, the usual suspects :

- if flash[:alert]
  ...
  - if flash[:url]
    = link_to "blah blah", flash[:url]

Upvotes: 11

shingara
shingara

Reputation: 46914

You can. You can add some Helper in your controller too.

Or you can do it by i18n system.

Upvotes: 0

Related Questions