代码之家  ›  专栏  ›  技术社区  ›  Trip

为什么这在IRB中起作用而不起作用?

  •  1
  • Trip  · 技术社区  · 15 年前

    我有用户。用户有很多:组织

    如果我这样做了:

    User.find(:all).select {|u| u.organizations.first.name }
    

    它返回:

    NoMethodError: You have a nil object when you didn't expect it!
    The error occurred while evaluating nil.name
    from (irb):33
    from (irb):33:in `select'
    from (irb):33
    

    1 回复  |  直到 15 年前
        1
  •  8
  •   Chris Bunch    15 年前

    因为你的一个用户没有任何组织所以organizations.first 是零

    你可以通过这样做来防止这种情况

    User.find(:all).select {|u| 
      u.organizations.first.name unless u.organizations.size == 0}
    
    推荐文章