【问题标题】:Problem accessing variable in a nested form partial以嵌套形式访问变量的问题部分
【发布时间】:2010-04-23 06:01:37
【问题描述】:

我在 Rails 视图中有一个嵌套表单,调用方式如下

<% f.fields_for :invoice_item_numbers do |item_no_form| %>
    <%= render 'invoice_item_number', :f => item_no_form %>
<% end %>

部分(_invoice_item_number.html.erb)看起来像这样

<div class='invoice_item_numbers'>
<% if f.object.new_record? %>
        <li><%= f.label :item_number %><%= f.text_field :item_number %>
    <%= link_to_function "remove", "$(this).parent().remove()", :class => 'remove_link' %></li>
<% else %>
    <li class="inline"><%= f.label :item_number %><%= f.text_field :item_number %>
    </li><li class="inline"><%= f.label :description %><%= invoice_item_number.description %></li><li><%= f.label :amount %><%= f.text_field :amount %>
    <%= f.check_box '_destroy', :class => 'remove_checkbox' %>
    <%= f.label '_destroy', 'remove', :class => 'remove_label' %></li>
<% end %>
</div>

此操作失败并显示错误消息

undefined method `description' for nil:NilClass

为什么 invoice_item_number 在这个部分返回一个 nil 对象?它显然是以某种方式定义的,因为如果我将其更改为其他内容(例如item_number.description,那么错误消息将变为undefined local variable or methoditem_number' for #instead. The invoice_item_number object that is being displayed by this partial is being used perfectly well by the form helpers asandboth work perfectly well. I have tried a number of solutions such as using@invoice_item_number` 并在渲染方法中显式定义一个对象,但这些都不起作用。

大概有一个非常简单的答案。

【问题讨论】:

    标签: ruby-on-rails forms partial-views nested-forms


    【解决方案1】:

    只需在http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes 重新阅读 Ryan 关于嵌套表单的剪贴簿留言即可找到答案。它已经在我的代码中,但我不明白发生了什么。我可以使用 f.object 访问 invoice_item_number 对象,因此将 &lt;%= invoice_item_number.description %&gt; 替换为 &lt;%= f.object.description %&gt; 解决了我的问题。

    【讨论】:

    • 没问题。我很感激你花时间阅读它。谢谢。
    • 是我还是大多数名为 Ryan 的“著名” Rails 开发人员? Ryan Bigg,Ryan Bates,Ryan Daigle.. wtf haha​​h
    【解决方案2】:

    改一下怎么样:

    <%= invoice_item_number.description %>
    

    <%= f.label :description %>
    

    或者如果你需要一个字段:

    <%= f.text_field :description %>
    

    【讨论】:

    • 好吧,我已经有 f.label :description 了。有趣的是,如果我确实放入了 f.text_field :description 这将完全按照我的意愿访问描述方法,但我不想要文本字段,我只想要文本。不过还是谢谢。
    • invoice_item_number 在部分中为零(尚未定义)。如果要访问模型数据,需要在控制器中定义@invoice_item_number 并通过@invoice_item_number.description 访问
    • 嗯,但在这种情况下 invoice_item_number 是一个嵌套属性。父属性(发票)在控制器中使用@invoice=Invoice.find(params[:id]) 定义。我真正想要访问的是 invoice.invoice_item_number.description 但我不知道如何在我的部分。
    • 你可以将多个参数传递给一个partial,语法是: 'invoice_item_number', :locals => { :f => item_no_form, :x => 123 } %> 那么你可以在局部变量中使用 x 作为局部变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2019-06-24
    相关资源
    最近更新 更多