1

我的模板中有这个

<% @clients.each do |client| %>
<li><%= link_to client.name, :controller => "client", :action => "show", :id => client.id %></li>
<%=YAML::dump(client.lastfull)%>
<% end %>

客户端看起来像这样:

class Client < ActiveRecord::Base
        set_table_name 'client'
        alias_attribute :id, :clientid
        set_primary_key :clientid


        has_many :jobs, :foreign_key => 'clientid', :order => 'starttime DESC'

        def lastfull
                jobs.first
        end
end

这有效,这是输出:

--- !ruby/object:Job attributes: jobid: "81" name: dobrak comment: "" endtime: 2012-06-20 10:15:04

但是当我尝试读取任何属性时,我得到错误:

undefined method `jobid' for nil:NilClass

职位类别:

class Job < ActiveRecord::Base
        attr_accessor :jobid

        set_table_name 'job'
        belongs_to :client

        has_one :status, :primary_key => 'jobstatus', :foreign_key => 'jobstatus'
end

我尝试添加返回属性的方法jobid并添加attr_accessor,但对我没有任何帮助。有什么建议么?谢谢你。

导轨 2.3.5

4

2 回答 2

2

看起来有些客户没有任何工作。如果将行更改为类似的内容会发生什么<%= client.lastfull.present? ? YAML::dump(client.lastfull.jobid) : 'client has no jobs' %>?你也可以看看Object#try

于 2012-06-20T08:55:02.470 回答
0

在输出 client#lastfull 的结果之前添加条件,如下所示:

<% if client.lastfull %>
  output job info here like <%= lastfull.jobid %> etc.
<% else %>
  no jobs available
<% end %>
于 2012-06-20T08:57:14.533 回答