gpt4 book ai didi

ruby-on-rails - railsfields_for渲染具有多个局部变量的局部变量,产生 undefined variable

转载 作者:行者123 更新时间:2023-12-04 03:13:31 25 4
gpt4 key购买 nike

全部,

我在使用标准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, f, 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, f, 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", locals.merge!(:f => builder))
end

link_to(name, "#", :class => "dynamic_add", 'data-association' => "#{association}",
'data-content' => "#{fields}")
end

现在,我的_form部分中的link_to_add_fields调用如下所示:
<%= link_to_add_fields "Add a comment", f, :comments, :tester => true %>

...然后我可以将字段动态添加到表单中,并传递其他本地变量。希望这会帮助其他人。

关于ruby-on-rails - railsfields_for渲染具有多个局部变量的局部变量,产生 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4248970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com