开发者

railscast 197 : error when trying to add fields with javascript

HI,

I tried to follow the 197: Nested Model Form Part 2 railscast 197 but i have this error when i try to add the field by javascript :

Uncaught SyntaxError: Unexpected token &

Here the helper :

  def link_to_add_fields(name, f, association)  
    new_ob开发者_JS百科ject = 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.singularize + "_fields", :f => builder)  
    end  
    link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))  
  end

And the javascript function :

function add_fields(link, association, content) {  
  var new_id = new Date().getTime();  
  var regexp = new RegExp("new_" + association, "g");  
  $(link).parent().before(content.replace(regexp, new_id));  
}

The call in my view :

- form_for @report do |f|
  %h1= f.label :name 
  %p= f.text_field :name
  - f.fields_for :requests do |builder|
    = render 'request_fields', :f => builder

  %p= link_to_add_fields "Add Request", f, :requests

Here is the html i get :

onclick="add_fields(this, "requests", "<div class=\'fields\'>\n  <h1><label for=\"report_requests_attributes_new_requests_query\">Query<\/label><\/h1>\n  <input id=\"report_requests_attributes_new_requests_query\" name=\"report[requests_attributes][new_requests][query]\" size=\"30\" type=\"text\" />\n  <input id=\"report_requests_attributes_new_requests__destroy\" name=\"report[requests_attributes][new_requests][_destroy]\" type=\"hidden\" value=\"false\" /><a href=\"#\" onclick=\"remove_fields(this); return false;\">remove<\/a>\n  <br>\n<\/div>\n"); return false;"

I tried to unescape it with CGI.unescapeHTML and i obtain that :

"add_fields(this, \"requests\", \"<div class='fields'>\n  <h1><label for=\"requests_query\">Query</label></h1>\n  <input id=\"requests_query\" name=\"requests[query]\" size=\"30\" type=\"text\" />\n  <input id=\"requests__destroy\" name=\"requests[_destroy]\" type=\"hidden\" value=\"false\" /><a href=\"#\" onclick=\"remove_fields(this); return false;\">remove</a>\n  <br>\n</div>\n\"); return false;"

All seems correct to me and i don't see where could be the problem. If someone has a idea.

Thanks,

Alain


You need to remove the h function that is escaping the HTML. In application_helper.rb:

link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))

should be

link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")


Use raw to escape JS properly in Rails 3+:

<%= raw(@stuff) %>

Just make sure what you’re escaping is safe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜