I am trying to have a model Method return information from an associated model. It works without any issues on the Rails console and also outputs the information on the console when it’s running as the web server.
To me it doesn’t seem very difficult. But it’s not working.
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'
Thanks
Do this:
Using your method, if the
Computerhas noip_addresses, then calling.firstwill returnnil, and there is noipmethod forNilClass(just like the error says). This way, it checks if there are anyip_addresses, and if so returns theipof the firstip_address, and if not returns nil.