【问题标题】:Rails 3 access nested attributes in nested formRails 3 以嵌套形式访问嵌套属性
【发布时间】:2011-10-12 16:38:46
【问题描述】:

我有一张 Invoice,其中包含属于 item Items 的 LineItems。

发票
client_id

订单项
invoice_id
item_id
数量
成本(因为可以根据需要编辑每张发票的成本)

物品
名称
费用

问题在于,在编辑表单中。我想显示费用和说明,但我不能。

_form.html.erb

<%= form_for(@invoice) do |f| %>  
  <div class="field">
    <%= f.label :organization_id, 'Client' %>
    <%= f.collection_select :client_id, @clients, :id, :name, :prompt => 'Select' %>
  </div>

<table id="invoice_items">
  <tr><th>Item</th><th>Description</th><th>Unit Cost</th><th>Qty</th></tr>
  <%= f.fields_for :line_items do |builder| %>
    <%= render 'line_item_fields', :f => builder %>
  <% end %>
  </table>
  <div class="actions">
    <%= f.submit 'Save', :disable_with => "Processing..." %>
  </div>
<% end %>

_line_items_fields.html.erb

<tr>
  <td><%= f.collection_select :item_id, @items, :id, :name, :prompt => '' %></td>
  <td>Description here</td>
  <td><%= f.text_field :cost, :class => 'cost' %></td>
  <td><%= f.text_field :quantity, :class => 'qty' %></td>
</tr>

如何在 _line_items_fields.html.erb 的 div 中显示成本和描述? 我需要在 div 中显示成本,因为稍后我需要使用它来让 jQuery 抓取该值进行一些计算。

【问题讨论】:

    标签: ruby-on-rails ruby forms


    【解决方案1】:

    我猜你正在寻找object

    类似:

    <%= f.object.cost unless f.object.cost.blank? %>
    

    【讨论】:

    • 谢谢!它适用于 LineItem,但我想更深入地访问一个级别:Item。如果我这样做 debug f.object.item 我可以看到 Item 属性,但如果我这样做 debug f.object.item.description 它告诉我这是一个 Nil 类。
    • 我猜你正在循环所有 line_items,有些可能没有项目。尝试:调试 f.object.item.try(:description)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多