我正在尝试在一个带有问题,答案和(多选)选项的系统中实现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个问题:
------ ------进展
如果我将函数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
答案 0 :(得分:3)
对于仍然有未定义方法`klass'为nil:NilClass 问题的人,请参阅以下主题 - has_many :through nested_form that can build multiple instances
答案 1 :(得分:1)
偶然发现了这个问题 - 如果它有用,请使用Ryan Bates的这个真棒nested form gem。
答案 2 :(得分:0)
你确定app ... js被包含在输出中吗?您可能需要编辑布局。
答案 3 :(得分:0)
在我的情况下,javascript没有被调用,我更改了:
的请求link_to name, '#', onclick: "add_fields(this,'#{association}','#{escape_javascript(fields)}')";
答案 4 :(得分:0)
您正在使用原型库语法而不是jQuery。访问剧集页面,查找提供原型和jQuery语法的代码部分。