所有,
我遇到了标准fields_for设置的问题.在我的“_form”部分我有:
<div class="comment_list"> <%= f.fields_for :comments do |cf| %> <%= render :partial => 'comments/comment_fields',:locals => {:f => cf,:tester => true} %> <% end %> <%= link_to_add_fields "Add a comment",f,:comments %> </div>
在“_comment_fields”部分中,我有通常的字段,然后是我的测试变量:
<%= tester.to_s %>
当我删除测试器变量时,一切都运行良好.一旦我添加测试变量,我就会收到此错误:
ActionView::Template::Error (undefined local variable or method `tester’ for #Class:0xa1f3664>:0xa1f1bd4>)
有没有其他人在使用具有多个本地的fields_for时遇到此问题?
为了详细说明,我的“_comment_fields”部分看起来像这样:
<div class="comment dynamic_field"> <span class="comment_content"><%= f.text_field :content,:class => "comment_content" %></span> <%= tester.to_s %> <%= link_to_remove_fields "remove",f %> </div>
它仅从“_form”部分调用.
解决方法
所有,
Hakunin是有钱的.我在不止一个地方打电话给我.第二个点是我的帮助方法“link_to_add_fields”.我用它来使用javascript添加字段.
方法看起来像这样:
# generates add fields on a dynamic form def link_to_add_fields(name,association,locals={}) 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(name,"#",:class => "dynamic_add",'data-association' => "#{association}",'data-content' => "#{fields}") end
请注意,这不允许将任何本地传递给render方法.我这样改了:
# generates add fields on a dynamic form def link_to_add_fields(name,locals.merge!(:f => builder)) end link_to(name,'data-content' => "#{fields}") end
现在我的_form部分中的link_to_add_fields调用如下所示:
<%= link_to_add_fields "Add a comment",:comments,:tester => true %>
…我可以动态地向表单添加字段并传递其他本地.希望,这将有助于其他人.