Ruby on rails nil类的未定义方法ip
我试图让一个模型方法从关联的模型返回信息。它在Rails控制台上工作时没有任何问题,并且在作为web服务器运行时也在控制台上输出信息 对我来说,这似乎并不难。但它不起作用Ruby on rails nil类的未定义方法ip,ruby-on-rails,methods,model,Ruby On Rails,Methods,Model,我试图让一个模型方法从关联的模型返回信息。它在Rails控制台上工作时没有任何问题,并且在作为web服务器运行时也在控制台上输出信息 对我来说,这似乎并不难。但它不起作用 class Computer < ActiveRecord::Base has_many :ip_addresses has_one :status def first_ip @computer = Computer.find(self.id) @computer.ip_addresses.
class Computer < ActiveRecord::Base
has_many :ip_addresses
has_one :status
def first_ip
@computer = Computer.find(self.id)
@computer.ip_addresses.first.ip
end
end
class IpAddress < ActiveRecord::Base
attr_accessible :ip
belongs_to :computers
end
[2011-10-10 16:09:02] ERROR ActionView::Template::Error: undefined method `ip' for nil:NilClass
/usr/local/lib/ruby/gems/1.8/gems/activesupport-3.0.10/lib/active_support/whiny_nil.rb:48:in `method_missing'
/Users/robertg/RubymineProjects/CMDBTEST/app/models/computer.rb:7:in `first_ip'
class计算机
谢谢请执行以下操作:
class Computer < ActiveRecord::Base
has_many :ip_addresses
has_one :status
def first_ip
first_ip_address = ip_addresses.first
first_ip_address ? first_ip_address.ip : nil
end
end
class计算机
使用您的方法,如果
计算机
没有ip\u地址
,则调用。首先
将返回nil
,并且NilClass
没有ip
方法(就像错误所说的那样)。这样,它会检查是否有ip\u地址
,如果有,则返回第一个ip\u地址
的ip
,如果没有,则返回零。@computer.ip\u地址数组的长度是多少。它有什么价值吗。似乎first返回nil,因此没有与计算机关联的ip地址。您不需要此位,@Computer=Computer.find(self.id)
。Self已经是一台计算机
;作为旁注,所属
关联应始终为单数,因为您只能引用一个ID。如果您真的希望IP地址
属于多台计算机,则应使用has\u和\u beliens\u to\u many
或双向has\u many:through
关联。您也可以使用try<代码>ip地址。首先。尝试(:ip)你说得对,这绝对是一种更简洁的方法。我想我最初的问题是,我试图访问尚未与任何实例变量关联的模型变量。