我正在尝试在带有问题、答案和(多选)选项的系统中实现 Ryan 的 Railscast #197。http://railscasts.com/episodes/197-nested-model-form-part-2。
- 我已经成功地实现了这些表单/部分之间的嵌套。
- 删除记录的更简单的“复选框”方法可以正常工作。
- 当我尝试添加/删除记录时会出现问题。
我已经完全按照他的 Railscast 中的代码复制了代码:
#new.html.erb
<%= javascript_include_tag :defaults, :cache => true %>
<% f.fields_for :in_options do |builder| %>
<%= render "option_fields", :f => builder %>
<% end %>
#_option_fields.html.erb partial
<%= f.hidden_field :_destroy %>
<%= link_to_function "remove", "remove_fields(this)" %>
#application_helper.rb (exact same as #197)
def link_to_remove_fields(name, f)
f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
end
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 (exact same as #197. I have an Event.addbehavior below this code.)
function remove_fields(link) {
$(link).previous("input[type=hidden]").value = "1";
$(link).up(".fields").hide();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).up().insert({
before: content.replace(regexp, new_id)
});
}
2个问题:
- 当我点击“删除”链接时,它并没有被删除——它只是向上或向下移动页面。
- 当我包含link_to_add_fields“添加答案”,f,:答案时,我得到nil:NilClass的未定义方法`klass'。
- - - 进步 - - -
如果我将函数 remove_fields(link) 移动到 new.html.erb 的顶部,则删除链接有效。这意味着,我在访问 application.js 中的函数时遇到问题。这是我的精简结构。
# layout forms.html.erb
<html>
<head>
<%= stylesheet_link_tag "global", "forms", "candidateCreateProfile", "LiveValidation", "formsAccount", :cache => true %>
<%= javascript_include_tag :defaults, "LiveValidation" %>
</head>
<body>
<%= yield %>
</body>
</html>
# new.html.erb
<%= stylesheet_link_tag "interviewQuestions" %>
<%= javascript_include_tag "effects", "lowpro", "toggle", :cache => true %>
...#everything else, including my call to remove_fields