Put a link in a flash[:notice]

后端 未结 8 1477
天涯浪人
天涯浪人 2020-12-04 23:31

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:

<
相关标签:
8条回答
  • 2020-12-05 00:06

    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"
    
    0 讨论(0)
  • 2020-12-05 00:11

    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:

    View

    <% 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">&times;</span></button>
        <div id="flash_<%= name %>"><%= sanitize(msg) %></div>
      </div>
    <% end %>
    

    Controller

    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.

    0 讨论(0)
  • 2020-12-05 00:13

    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}."
    
    0 讨论(0)
  • 2020-12-05 00:24

    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

    0 讨论(0)
  • 2020-12-05 00:24

    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

    0 讨论(0)
  • 2020-12-05 00:26

    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}"
    
    0 讨论(0)
提交回复
热议问题