I am learning Ruby and Rails.
I have a Ruby on Rails project that tracks jobs a server is running. Right now, when I manually create a new job, it announces:
<Building on Dorian's answer, here's an internationalized flash with a link in it:
flash[:notice] = t('success', go: view_context.link_to(t('product'), @product)).html_safe
Where your translation (e.g. a YAML file) might contain:
en:
success: "Successfully created a %{go}"
product: "product"
it:
success: "%{go} creato con successo"
product: "Prodotto"
The selected answer didn't work for me. But the answer from this post worked. I'm using Rails 4.2.4
by the way. With guidance from the answer I linked, here's how I did it:
<% flash.each do |name, msg| %>
<div class="alert alert-<%= name %>">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<div id="flash_<%= name %>"><%= sanitize(msg) %></div>
</div>
<% end %>
flash[:success] = "Blah blah. #{view_context.link_to('Click this link', '/url/here')}"
The magic is the sanitize
method.
I didn't need to use .html_safe
as well.
You can always use the Rails link_to helper:
flash[:notice] = "Created job job number #{link_to update.id, :controller => 'jobs', :action => 'list', :job => update.id}."
Don't forget to add .html_safe
at the end of the notice, if you're using Rails3.
So it would say flash[:notice] = "Your message".html_safe
You can use an alias in your controller to the link_to function, or the RailsCast recipe:
"Created job job number #{@template.link_to update.id,
:controller => 'jobs', :action => 'list', :job => update.id}."
http://railscasts.com/episodes/132-helpers-outside-views
As nas commented, link_to
is not available from your controller unless you include the appropriate helper module, but url_for
is. Therefore I'd do pretty much what Emily said except use url_for
instead of hardcoding a URL.
e.g. if a job were defined as a resource in your routes:
link = "<a href=\"#{url_for(update)}\">#{update.id}</a>"
flash[:notice] = "Created job number #{link}"