为什么尝试抛出错误?这不是违背了整个目的吗?也许它只是在控制台中?
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 RubyObject#send
does.Unlike that method however, a
NoMethodError
exception will not be raised andnil
will be returned instead, if the receiving object is anil
object orNilClass
.
以及
try
that is patched into NilClass
的版本:try(*args)
Callingtry
onnil
always returnsnil
.
所以
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 returnsnil
rather than raising an exception.
所以现在
try
同时处理两项检查。如果你想要 Rails 3 的行为,有 try!
:Same as
try
, but will raise aNoMethodError
exception if the receiving [sic] is notnil
and does not implemented [sic] the tried method.
关于ruby-on-rails - rails < 4.0 "try"方法抛出 NoMethodError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7426808/