【问题标题】:Render partial with locals inside a form_for tag在 form_for 标记内使用本地人渲染部分内容
【发布时间】:2015-11-18 23:36:50
【问题描述】:

我有这个表格(简体)

<%= form_for @client do |client| %>
 <%= render "some_partial", foo: 10, bar: 20 %>
<% end %>

我也尝试使用:&lt;%= render :partial =&gt; "some_partial", :locals =&gt; {foo: 10, bar: 20} %&gt;

some_partial:

<%= foo %>
<%= bar %>

但是,部分变量不可用:

undefined local variable or method `foo' for #<#<Class:0x007fb35027bbd0>:0x007fb350536e60>

如果我将render 放在form_tag 之外就可以了

提前致谢

UPDATE1:在表格的最后,我有这个:

&lt;%= link_to_add_association 'Add', client, :client_addresses, class: "ui mini green button add_client_address" %&gt;

如果我删除这部分,工作正常...

【问题讨论】:

  • 您使用的 Cocoon gem 对吗?你能发布完整的表单代码吗?

标签: ruby-on-rails


【解决方案1】:

您必须将参数作为本地人提及,就像这样。

<%= render :partial => "some_partial", :locals => {foo: 10, bar: 20} %>

【讨论】:

  • 嗨,我也已经试过了。抱歉没提。我会更新问题。
  • 出于奇怪的原因,我只有在删除它时才有效:`` ``
【解决方案2】:

"some_partial" 是否与您尝试使用 link_to_add_association 加载的 :client_addresses 相同?

我相信您遇到的错误消息来自link_to_add_association

您似乎正在使用Cocoon gem。为了将本地变量传递到 Cocoon 使用的部分(在您的情况下为 :client_addresses),您需要为 link_to_add_association 传递参数 render_options: { locals: {foo: bar}

【讨论】:

  • 两个部分都是client_addresses。关于render_options。但是我需要在渲染视图时传递本地人,而不是在点击 link_to_add_association 时。
  • Cocoon 将render 部分页面加载。当您单击link_to_add_association 时不是如果locals 不存在于link_to_add_association 声明中,它将导致您看到的错误。由于您正在加载与 &lt;%= foo %&gt; &lt;%= bar %&gt; 相同的 client_addresses 部分,因此预计将传入这些本地变量。[这里] (github.com/nathanvda/cocoon#render_options) 是来自 Cocoon 的文档。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-17
  • 2020-04-01
  • 2018-04-30
  • 2015-11-28
  • 2011-11-03
  • 2017-09-02
  • 1970-01-01
相关资源
最近更新 更多