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)

            end

        end

    end

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.

Tejus Parikh

I'm a software engineer that writes occasionally about building software, software culture, and tech adjacent hobbies. If you want to get in touch, send me an email at [my_first_name]@tejusparikh.com.