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, &quot;skills&quot;, &quot;&lt;label for=\&quot;user_skills_attributes_new_skills_name\&quot;&gt;Skill&lt;\/label&gt;\n&lt;input data-autocomplete=\&quot;/users/autocomplete_skills_vocab_name\&quot; id=\&quot;user_skills_attributes_new_skills_name\&quot; name=\&quot;user[skills_attributes][new_skills][name]\&quot; size=\&quot;30\&quot; type=\&quot;text\&quot; /&gt;&lt;br /&gt;\n&lt;input id=\&quot;user_skills_attributes_new_skills__destroy\&quot; name=\&quot;user[skills_attributes][new_skills][_destroy]\&quot; type=\&quot;hidden\&quot; value=\&quot;false\&quot; /&gt;&lt;a href=\&quot;#\&quot; onclick=\&quot;remove_fields(this); return false;\&quot;&gt;remove&lt;\/a&gt;&quot;); return false;">Add a Skill</a>
EDIT/
Figured it out -- For Rails 3 remove h()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With