Sanitizing Trix input

522 views Asked by At

Under Rails 5.1 I am using Trix to allow users to edit their 'legal conditions'. Then I am trying to sanitize this 'legal' parameter in my controller before the user record is updated, but end up with :

undefined method `sanitize'

Here the code :

params[:user][:legal] = sanitize params[:user][:legal], tags: %w(strong div strong br li ul)

def user_params
  params.require(:user).permit(:presentation, :linktowebsite, :legal)
end

Don't see anything different than normal usage shown here : http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

1

There are 1 answers

0
spong On

You are not using sanitize correctly. sanitize is used in the view, not in the controller.

To use it correctly, your model should allow a field to save html input from the user, but you want to "clean" it when it's used in the view so that unsafe or non-whitelisted tags/attributes is prevented from being sent/displayed to the user.

If you are looking to remove html tags/attributes before it gets saved, you may want to look at strip_tags.

strip_tags("Strip <i>these</i> tags!")
# => Strip these tags!

strip_tags("<b>Bold</b> no more!  <a href='more.html'>See more here</a>...")
# => Bold no more!  See more here...

strip_tags("<div id='top-bar'>Welcome to my website!</div>")
# => Welcome to my website!