扁平哈希中的访问/输出值?

时间:2012-03-29 18:59:29

标签: ruby-on-rails ruby hash

在我的控制器中我有:

@invoices = current_user.account.clients.map(&:invoices).flatten

并在我的index.html.erb中我想显示值,目前我有以下内容:

<% @invoices.each do |invoice| %>
    <tr>
        <td></td>
        <td><%= invoice.client.name %></td>
        <td><%= invoice.jobs.inspect %></td> #HERE IS WHERE I WANT START_DATE, etc
        <td><%= invoice.created_at %></td>
        <td><%= link_to "PDF", invoice_path(invoice, :format => :pdf)%></td>
        <td><%= link_to invoice, :method => :delete, :confirm => 'Are you sure you want to delete this invoice' do %> <i class="icon-trash"></i><% end %>
    </td>
    </tr>
  <% end %>

invoice.jobs.inspect返回以下内容:

[#<Job id: 15, start_date: "2012-03-24", due_date: "2012-03-31", notes: "grthryrth", audio_file_url: "1.txt", transcribed_file_url: "300.txt", status: "invoiced", account_id: 1, user_id: 1, client_id: 2, created_at: "2012-03-29 18:03:14", updated_at: "2012-03-29 18:40:49", invoice_id: 6>, #<Job id: 16, start_date: "2012-03-24", due_date: "2012-03-21", notes: "uopuiouioiio", audio_file_url: "Data Flow Analysis and Integration v1.1.docx", transcribed_file_url: "ECA-Sponsor Monthly Agenda 20120105.doc", status: "invoiced", account_id: 1, user_id: 4, client_id: 2, created_at: "2012-03-29 18:05:24", updated_at: "2012-03-29 18:40:49", invoice_id: 6>]

如何单独访问每个值,例如invoice.jobs.start_date?谢谢!

2 个答案:

答案 0 :(得分:1)

如果您想获取发票,那么浏览用户模型似乎是向后退的。请考虑这样的事情:

@invoices = Invoice.joins( :client => { :accounts => :user } ).
                    include( :client, :jobs ).
                    where( "accounts.user_id" => current_user.id ).
                    all

但是,无论哪种方式,如果invoice.jobs是一个数组(由其为复数和其inspect输出中的方括号所证明),那么您首先需要使用例如数组来访问数组的元素。 [0]first

invoice.jobs.first.start_date
# => "2012-03-24"

答案 1 :(得分:0)

有多种方法可去:你可以在你的工作模型中覆盖inspect,创建另一种方法(如pretty_display,等等),如果你不想搞砸{{1或者使用视图助手(类似inspect)。我会选择第3个选项。