ruby-on-rails - ActiveRecord 关系 : undefined method for nil:NilClass

标签 ruby-on-rails activerecord

考虑以下几点:

class Manager < ActiveRecord::Base
  has_many :employees
end
class Employee < ActiveRecord::Base
  belongs_to :manager
end


employee = Employee.first
puts employee.manager.name

如果由于某种原因员工没有经理,我会得到这个:

undefined method `name' for nil:NilClass

这是有道理的。但是,有没有一种干净/建议的方法来处理这个问题,这样我就不必总是在询问经理的姓名之前检查并查看员工是否真的有经理?<​​/p>

最佳答案

尝试:

puts employee.manager.name unless employee.manager.nil?

或者:

puts (employee.manager.nil? ? "No manager" : employee.manager.name)

在这种情况下相当于:

puts (employee.manager ? employee.manager.name : "No manager")

(等同于employee.manager不能返回false。)

关于ruby-on-rails - ActiveRecord 关系 : undefined method for nil:NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16450698/

相关文章:

sql - rails : View ActiveRecord's resulting query

ruby-on-rails - 如何在事件记录 where 子句中使用通配符同时防止 sql 注入(inject)

ruby-on-rails - 如何在 ActiveRecord 中为 INSERT ONLY 语句跳过事务?

ruby-on-rails - Rails 回形针 `is not recognized by the ' 识别'命令`

ruby-on-rails - 以 Rails 方式实现通知模型

mysql - 当类型 "rake db:migrate"获得错误的文件描述符时出现错误

ruby-on-rails - 将现有的 Rails 路由/应用程序迁移到 emberjs

ruby-on-rails - ActiveRecord::StatementInvalid (PG::UndefinedFunction

ruby-on-rails - 具有单表继承的 Rails ActiveRecord_Associations_CollectionProxy

ruby-on-rails - Rails - 如何禁用对本地主机 :3000/users/sign_in on Devise gem? 的访问