我想從一個關聯的模型中返回信息。它在Rails控制檯上沒有任何問題,並且在作爲Web服務器運行時在控制檯上輸出信息。未定義的方法ip爲零類
對我來說,這似乎並不困難。但它不起作用。
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'
感謝
@ computer.ip_addresses數組的長度是多少。它有沒有任何價值。似乎首先返回零,所以沒有IP地址與計算機相關聯。 – Jayendra
你不需要這個位,'@computer = Computer.find(self.id)'。 Self已經是'Computer'; P – diedthreetimes
作爲一個附註,'belongs_to'關聯應該總是單數,因爲你只能引用一個ID。如果你真的想要一個'IpAddress'屬於多臺計算機,你應該使用'has_and_belongs_to_many'或者雙向'has_many:through'關聯。 – bricker