Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent rails from converting special characters to HTML entities

I'm using the following helper function, but it seems to convert all the special characters in my JavaScript statement to HTML entities, rendering it useless and broken. Any suggestions?

 def link_to_add_fields(name, f, association)
    new_object = f.object.class.reflect_on_association(association).klass.new
    fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
      render(association.to_s + "_fields", :f => builder)
    end
    link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
  end

The above generates a link like this (notice the conversions to $amp; - " etc:

<a href="#" onclick="add_fields(this, &amp;quot;skills&amp;quot;, &amp;quot;&amp;lt;label for=\&amp;quot;user_skills_attributes_new_skills_name\&amp;quot;&amp;gt;Skill&amp;lt;\/label&amp;gt;\n&amp;lt;input data-autocomplete=\&amp;quot;/users/autocomplete_skills_vocab_name\&amp;quot; id=\&amp;quot;user_skills_attributes_new_skills_name\&amp;quot; name=\&amp;quot;user[skills_attributes][new_skills][name]\&amp;quot; size=\&amp;quot;30\&amp;quot; type=\&amp;quot;text\&amp;quot; /&amp;gt;&amp;lt;br /&amp;gt;\n&amp;lt;input id=\&amp;quot;user_skills_attributes_new_skills__destroy\&amp;quot; name=\&amp;quot;user[skills_attributes][new_skills][_destroy]\&amp;quot; type=\&amp;quot;hidden\&amp;quot; value=\&amp;quot;false\&amp;quot; /&amp;gt;&amp;lt;a href=\&amp;quot;#\&amp;quot; onclick=\&amp;quot;remove_fields(this); return false;\&amp;quot;&amp;gt;remove&amp;lt;\/a&amp;gt;&amp;quot;); return false;">Add a Skill</a>

EDIT/

Figured it out -- For Rails 3 remove h()

like image 760
stewart715 Avatar asked Apr 21 '11 12:04

stewart715


1 Answers

In Rails 2, output by default was not escaped. The h() method does this. In Rails 2 views, you often see the following:

<%=h @object.field %>

However, in Rails 3 output is now escaped by default. You no longer need the h() method. In order to get unescaped output you have to use the raw method.

More information is available here: http://railscasts.com/episodes/204-xss-protection-in-rails-3

So basically in your case you were looking at Rails 2 code and the removal of the h() is needed to update it for Rails 3.

like image 106
Mark Thomas Avatar answered Sep 25 '22 00:09

Mark Thomas