2011-04-04 42 views
0

我看到this railscast中的一些註解,該解決方案對Rails 3和jQuery不起作用,但目前尚不清楚。這是我在控制檯:得到錯誤Railscasts與Rails 3不兼容?需要幫助調試

Uncaught ReferenceError: add_fields is not defined 
(anonymous function)485:98 
onclickd 

它指出了這個鏈接是很長的和奇怪:<a href="#" onclick="add_fields(this, 'comment_titles', '&amp;lt;p class=\&amp;quot;fields\&amp;quot;&amp;gt;\n&amp;lt;label for=\&amp;quot;video_comment_titles_attributes_new_comment_titles_title\&amp;quot;&amp;gt;Comment Title:&amp;lt;\/label&amp;gt; \n&amp;lt;input id=\&amp;quot;video_comment_titles_attributes_new_comment_titles_title\&amp;quot; name=\&amp;quot;video[comment_titles_attributes][new_comment_titles][title]\&amp;quot; size=\&amp;quot;30\&amp;quot; type=\&amp;quot;text\&amp;quot; /&amp;gt;\n&amp;lt;input id=\&amp;quot;video_comment_titles_attributes_new_comment_titles__destroy\&amp;quot; name=\&amp;quot;video[comment_titles_attributes][new_comment_titles][_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;\n&amp;lt;input id=\&amp;quot;add_comment_title\&amp;quot; name=\&amp;quot;commit\&amp;quot; type=\&amp;quot;submit\&amp;quot; value=\&amp;quot;Add\&amp;quot; /&amp;gt;\n &amp;lt;div class=\'hint\'&amp;gt;Let your listeners know what comments you want by adding a guiding title for them. Pose a question, ask for feedback, or anything else!&amp;lt;\/div&amp;gt;\n&amp;lt;\/p&amp;gt;'); return false;">New Comment Title</a>

它這是該鏈接在我的視頻節目的看法:

<%= link_to_add_fields "New Comment Title", f, :comment_titles %> 

這是在我的應用助手link_to_add_fields方法:

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.singularize + "_fields", :f => builder) 
    end 
    link_to_function(name, h("add_fields(this, '#{association}', '#{escape_javascript(fields)}')")) 
end 

這是場功能在我的application.js附加:從railscast

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)); 
    } 

我幾乎複製並粘貼所以我不知道發生了什麼事。

我該如何解決這個問題?你還想看什麼其他的代碼?

+1

你的問題似乎是在你的application.js所以修復它,你可以在以後調用你的add_fields方法。 – shingara 2011-04-04 06:37:30

回答

3

所以它看起來像:

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)); 
} 

必須是的的的document.ready()塊之外。

+0

這是因爲add_fields不是匿名函數。它在文檔準備好之前單擊鏈接時應用。 – 2013-04-26 14:36:32