Rails的web-app-theme 驗證消息顯示

[b]web-app-theme[/b] 是一個用於快速開發Rails應用的後臺模板.比Django的後臺要靈活的多了.

web-app-theme有點小缺點,就是字段驗證的消息沒有顯示的樣式,只有FLASH消息顯示的樣式.

想到一個簡單的解決方案,不用修改webp-ap-theme樣式,就是把errors添加到flash,通過flash的樣式來顯示errors消息.

通過eval方法,用到了一點點元編程.一行代碼就好了.比JAVA實現簡單了N倍,具體請看代碼

修改module ApplicationHelper,添加下面方法.
def add_errors_to_flash_now
model_name = controller_name[0...-1]
model = nil
eval("model = @#{model_name}")
if model.class.method_defined? :errors
if model.errors.any?
flash.now[:error] = []
model.errors.full_messages.each { |msg|
flash.now[:error] << msg
}
end
end
end


修改application.html.erb,把顯示flash消息的代碼改成如下:
<div class="flash">
<% add_errors_to_flash_now %>
<% flash.each do |type, message| -%>
<div class="message <%= type %>">
<% if message.instance_of? Array %>
<% message.each do |msg| %>
<p><%= msg %></p>
<% end %>
<% else %>
<p><%= message %></p>
<% end %>
</div>
<% end -%>
</div>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章