导轨< 4.0“尝试”方法抛出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
而不是抛出错误?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Rails 3
您误解了
try
的工作原理,来自 精美手册:以及
try
的版本被修补到 <代码>NilClass:因此
try
不会忽略您对对象调用不存在的方法的尝试,它会忽略您对nil
调用方法的尝试并返回nil< /code> 而不是引发异常。
try
方法只是一种避免在方法调用链中的每一步都检查nil
的简单方法。Rails 4
Rails 4 中
try
的行为发生了变化,所以现在:所以现在
try
可以同时处理这两项检查。如果您想要 Rails 3 的行为,可以尝试!
:
Rails 3
You misunderstand how
try
works, from the fine manual:And the version of
try
that is patched intoNilClass
:So
try
doesn't ignore your attempt to call a non-existent method on an object, it ignores your attempt to call a method onnil
and returnsnil
instead of raising an exception. Thetry
method is just an easy way to avoid having to check fornil
at every step in a chain of method calls.Rails 4
The behavior of
try
has changed in Rails 4 so now it:So now
try
takes care of both checks at once. If you want the Rails 3 behavior, there istry!
:这就是尝试所做的
因此,假设您在控制器中设置了
@user
但没有实例化它,然后@user.try(:foo)
而不是=> nil
这里重要的一点是 try 是一个实例方法。它还如果您尝试的对象不是 nil,则不会返回 nil。
This is what try does
So, let's say you setup
@user
in your controller but you didn't instantiate it then@user.try(:foo)
instead of=> nil
The important point here is that try is an instance method. It also doesn't return nil if the object you try on isn't nil.
我知道这已经过时了,但它可能对其他人有帮助,因为这是我用谷歌搜索这个问题时出现的第一件事。我“借用”了 try 的代码,并实现了我自己的 try_method 方法,其行为就像 try 一样,只不过它首先检查是否方法在调用send之前就存在。我在 Object 中实现了这个并将其放入初始值设定项中,现在我可以在任何对象上调用它。
I know this is old, but it may help somebody else, because this is the first thing that popped up when I Googled this issue. I "borrowed" the code for try and implemented my own try_method method which acts just like try, except that it first checks to see if the method exists before calling send. I implemented this in Object and put it in an initializer, and I can now call it on any object.