Glenn Gillen有一種方法,他稱Useful Flash Messages in Rails。
我修改了他的代碼片段,使其更具慣用性(至少對我而言)。
控制器填補這樣的閃光:
flash[:notice] = "Your profile was updated. %s"
flash[:notice_item] = ["Edit again?", edit_profile_path(@profile)]
然後,您可能有幫手,看起來是這樣的:
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
視圖看上去簡直像這樣:
<%= render_flash_messages(:error, :notice, :warning) %>
視圖(通過flash_message_with_item
助手)負責創建錨標記,但是控制器管理進入閃光消息的內容,包括進一步操作的可選資源。
謝謝你。真棒。 – Dty 2011-08-24 18:16:58
感謝您使用rails 3.1回答更新這個問題! – jpwynn 2012-01-23 08:18:14
將其作爲新的接受答案。這比我之前採取的方式更加清晰。我不知道'view_context'訪問器。 – 2012-01-27 16:18:23