2011-10-12 87 views
0

或者你真的需要單獨清理每個領域?謝謝Rails - 保存到數據庫時,是否有一種方法可以從所有字段中去除HTML?

+0

什麼是與單獨做每一個問題了嗎?你是什​​麼意思?如果您必須遍歷字符串集合並將'strip_tags'應用於每個字符串,那麼這是一個問題嗎? – bdares

+1

我可以說15個模型,每個平均5個領域。我不想在每個領域的早期模型類中進行消毒。我想默認保存sanatize,只有當我允許它支持HTML。思考? – AnApprentice

回答

4

您可以使用列元數據遍歷每列。

(從http://blog.hulihanapplications.com/browse/view/10-strip-html-in-ruby-on-rails):

class Product < ActiveRecord::Base 

before_save :strip_html 
def strip_html # Automatically strips any tags from any string to text typed column 
    include ActionView::Helpers::SanitizeHelper 
    for column in Product.content_columns 
    if column.type == :string || column.type == :text # if the column is text-typed 
     if !self[column.name].nil? # strip html from string if it's not empty 
     self[column.name] = strip_tags(self[column.name]) 
     end 
    end 
    end 
end 
相關問題