Stripping HTML Tags from your ActiveModel Model

Posted by Tejus Parikh on March 29, 2011

Finally a Rails post! This one is short, basic, and probably has a bunch of other examples on the net. Rails3 escapes HTML by default, so this isn’t strictly necessary, but I still believe that what goes into the datastore should be clean. After all, the data will probably last longer than the front-end. I found this post that explains how to do it for your ActiveRecord models. However, I don’t have columns. Instead I used the following before_filter in my model class.

    before_save :sanitze_html

    def sanitze_html

        @attributes.each_key do |attr|

            value = @attributes[attr]

            if(value.class == String)

                @attributes[attr] = strip_tags(value)




It’s the same idea, but instead use the attribute map to pull the objects out. If it’s a String type, call strip_tags.

Related Posts:

Tejus Parikh

Tejus is an software developer, now working at large companies. Find out when I write new posts on twitter, via RSS or subscribe to the newsletter: