ruby-on-rails - rails < 4.0 "try"方法抛出 NoMethodError?

标签 ruby-on-rails rails-activerecord nomethoderror

为什么尝试抛出错误?这不是违背了整个目的吗?也许它只是在控制台中?

ruby-1.9.2-p180 :101 > User.first.try(:something)
NoMethodError: undefined method `something' for #<User:0x000001046ad128>
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/activemodel-3.0.10/lib/active_model/attribute_methods.rb:392:in `method_missing'
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/activerecord-3.0.10/lib/active_record/attribute_methods.rb:46:in `method_missing'
    from (irb):101
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.10/lib/rails/commands/console.rb:44:in `start'
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.10/lib/rails/commands/console.rb:8:in `start'
    from /Users/me/.rvm/gems/ruby-1.9.2-p180/gems/railties-3.0.10/lib/rails/commands.rb:23:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

编辑:

谢谢大家,现在我明白了。

有没有办法在不使用 respond_to? 的情况下做我想做的事,使得 User.try(:something)返回 nil而不是抛出错误?

最佳答案

rails 3

你怎么理解try作品,来自 fine manual :

try(*a, &b)
Invokes the method identified by the symbol method, passing it any arguments and/or the block specified, just like the regular Ruby Object#send does.

Unlike that method however, a NoMethodError exception will not be raised and nil will be returned instead, if the receiving object is a nil object or NilClass.



以及 try that is patched into NilClass 的版本:

try(*args)
Calling try on nil always returns nil.



所以try不会忽略您在对象上调用不存在的方法的尝试,它会忽略您在 nil 上调用方法的尝试并返回 nil而不是引发异常。 try方法只是一种避免必须检查 nil 的简单方法。在方法调用链的每一步。

rails 4
try的行为在 Rails 4 中发生了变化,所以现在它:

Invokes the public method whose name goes as first argument just like public_send does, except that if the receiver does not respond to it the call returns nil rather than raising an exception.



所以现在try同时处理两项检查。如果你想要 Rails 3 的行为,有 try! :

Same as try, but will raise a NoMethodError exception if the receiving [sic] is not nil and does not implemented [sic] the tried method.

关于ruby-on-rails - rails < 4.0 "try"方法抛出 NoMethodError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7426808/

相关文章:

css - 中间人:动态背景图?

html - 两种形式具有相同的作用

ruby-on-rails - 我可以将 PostgreSQL 的 "Special Date/Time Inputs"与 ActiveRecord 一起使用吗?

python - 在 Ruby 中,为什么 `Array.length` 会给出 NoMethodError?

ruby-on-rails - 为什么我的 rails if/else 得到 NoMethodError

ruby-on-rails - SELECT DISTINCT 的 PG 错误,尝试在 Heroku 上查看时,ORDER BY 表达式必须出现在选择列表中

mysql - rails : ActiveRecord class throws "NameError: uninitialized constant" - Is this a naming issue?

ruby-on-rails - 如何使用属性 API 设置虚拟属性的默认值

ruby-on-rails - Rails 6 ActiveStorage 在文件上传失败时恢复事务

ruby-on-rails - 在 Rails 中使用复选框