Neil Neil - 3 months ago 31
Ruby Question

Strip out script tags before saving to database in rails

For all my models application wide: If the user submits a text_field or text_area containing

<script></script>
tags, then I want rails to strip those tags before saving the user's data entry into the database.

I have already looked at the following posts which are all around 5 years old:



I have also looked at the following docs, but I haven't figured out how to apply them to this situation (removing script tag prior to persisting to database):



Example:

I
scaffold
for a
user
resource:

rails g scaffold user first_name last_name age:integer bio:text


The user then inputs the following and submits it:

user_input

The following should be saved to the database for each attribute of this
user
record:


  • first_name: Foo

  • last_name: Foo

  • age: 5

  • bio: Bazz



Thanks!

Answer

If you just want to sanitize when rendering in the HTML, RoR already comes with a helper (http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html) that lets you clean those tags automatically.

If you want them clean those bio fields before storing them in your database, there is a gem (sanitize) which will make it easy. That gem lets you configure which tags you want to preserve (if any) and blacklists the rest.

-- with strong_params you usually have a helper method in your controller in order to require and permit attributes. After being permitted, you could traverse over those params and check some (or all of them)

# using the sanitize gem
def sanitize input_field
  Sanitize.fragment(input_field, Sanitize::Config::RELAXED)
end

def sanitize_product_input 
  # product_params = strong_params filter
  [:first_name, :last_name, :bio].each do |field|
    product_params[field] = sanitize(product_params[field])
  end
  product_params
end

or you could do this a bit more generic and create in your application_controller a new method to sanitize inputs

# using the sanitize gem
def sanitize input_field
  Sanitize.fragment(input_field, Sanitize::Config::RELAXED)
end

def sanitize_input input_params, fields
  fields.each do |field|
    input_params[field] = sanitize(input_params[field])
  end
end

and use that in the methods were you are defining your strong_params filters

def product_params 
  fields = [:first_name, :last_name, :bio]
  input_params = params.require(:product).require(fields)
  sanitize_input(input_params, fields)
  input_params
end