我正在为ActiveRecord :: Relation获取一个未定义的方法。我在模特中遗漏了什么吗?

时间:2014-05-25 23:57:55

标签: ruby-on-rails activerecord

我在尝试使用db关系时得到一个未定义的方法。我在模特中遗漏了什么吗?

undefined method `hostname' for #<ActiveRecord::Relation:0x007f571c40ad10>
Extracted source (around line #101):

98:       <% @event.each do |events| %>
99:           <tr>
100:             <td class='timestamp'><%= events.timestamp %></td>
101:             <td class='sensor_name'><%= events.ips_sensors.hostname %></td>
102:             <td class='sig'><%= events.ips_signatures.sig_id %></td>
103:             <td class='sig_class'><%= events.ips_signatures.sig_class %></td>

控制器代码;

class IpsDashboardController < ApplicationController

  def ips_dashboard    
    @event = IpsEvent.all
  end
end

事件表;

class IpsEvent < ActiveRecord::Base
  attr_accessible :sid, :cid, :signature, :timestamp
  self.table_name = 'event'
  has_many :ips_sensors
  has_many :ips_signatures
end

传感器表;

class IpsSensor < ActiveRecord::Base
  attr_accessible :sid, :hostname, :interface
  self.table_name = 'sensor'
end

签名表;

class IpsSignature < ActiveRecord::Base
  attr_accessible :sig_id, :sig_name, :sig_class_id, :sig_priority, :sig_rev, :sig_gid
  self.table_name = 'signature'
end

1 个答案:

答案 0 :(得分:1)

您要求IpsEvent提供ips_sensors,其中会返回IpsSensor个型号的集合。大概IpsSensor有一个hostname,但集合却没有。{/ p>

循环遍历每个传感器,或选择一个并打印其主机名。

对于后续行,您会遇到同样的问题,您要求ips_signatures的整个集合查找仅在每个模型上定义的属性。