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: 开发者_StackOverflowundefined 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:
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
Using your method, if the Computer
has no ip_addresses
, then calling .first
will return nil
, and there is no ip
method for NilClass
(just like the error says). This way, it checks if there are any ip_addresses
, and if so returns the ip
of the first ip_address
, and if not returns nil.
精彩评论