What approach do you take for embedding links in flash messages?

試著忘記壹切 提交于 2019-11-30 00:11:25

Just thought I would share this, since found answer I was looking for elsewhere:

Works on rails 3.1

flash[:notice] = "Proceed to #{view_context.link_to('login page', login_path)}".html_safe

Glenn Gillen has an approach that he calls Useful Flash Messages in Rails.

I modified his code snippets to be a little more idiomatic (for me at least).

The controller fills the flash like this:

flash[:notice]      = "Your profile was updated. %s"
flash[:notice_item] = ["Edit again?", edit_profile_path(@profile)]

You then might have helpers that look something like this:

def render_flash_messages(*keys)
  messages = keys.collect do |key|
    content_tag(:p, flash_message_with_item(key), :class => "flash #{key}") if flash[key]
  end.join
  content_tag(:div, messages, :id => "flash_messages") unless messages.blank?
end

def flash_message_with_item(key)
  item = flash["#{key}_item".to_sym]
  substitution = item.is_a?(Array) ? link_to(*item) : item
  flash[key] % substitution
end

The view looks simply like this:

<%= render_flash_messages(:error, :notice, :warning) %>

The view (via the flash_message_with_item helper) is responsible for creating the anchor tag, but the controller manages what goes into the flash message including an optional resource for further action.

You could create a helper method to render out partials based on the value passed back in the flash message.

masonforest

This is similar to link_to() in Rails flash

# In your controller
flash[:error] = render_to_string(:partial => "sessions/login_failed_message")

# In sessions/_login_failed_message.html.erb
Login failed.  If you have forgotten your password, you can #{link_to('reset it', reset_path)}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!