2011-10-10 89 views
1

我想從一個關聯的模型中返回信息。它在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' 

感謝

+0

@ computer.ip_addresses數組的長度是多少。它有沒有任何價值。似乎首先返回零,所以沒有IP地址與計算機相關聯。 – Jayendra

+0

你不需要這個位,'@computer = Computer.find(self.id)'。 Self已經是'Computer'; P – diedthreetimes

+0

作爲一個附註,'belongs_to'關聯應該總是單數,因爲你只能引用一個ID。如果你真的想要一個'IpAddress'屬於多臺計算機,你應該使用'has_and_belongs_to_many'或者雙向'has_many:through'關聯。 – bricker

回答

2

這樣做:

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 

用你的方法,如果Computer沒有ip_addresses,然後調用.first將返回nil,並沒有ip方法NilClass(只就像錯誤說的那樣)。這樣,它會檢查是否有任何ip_addresses,如果是,則返回ip_addressip,如果不是,則返回nil。

+1

你也可以使用try。 'ip_addresses.first.try(:ip)' – diedthreetimes

+0

你說得對,那絕對是一個更簡潔的方法。 – bricker

+0

我想我最初的問題是我試圖訪問尚未與任何實例變量關聯的模型變量。 –

相關問題