Rails 3 对象#尝试不工作? [英] Rails 3 Object#try not working?
问题描述
我应该从哪里开始寻找?这就是让我相信这一点的原因:
Where should I start looking? Here's what makes me believe that:
0 urzatron work/secret_project % rails c
Loading development environment (Rails 3.1.3)
irb(main):001:0> t = Tag.new(:name => "!Blark!")
=> #<Tag id: nil, name: "!Blark!", created_at: nil, updated_at: nil>
irb(main):002:0> t.try(:name)
=> "!Blark!"
irb(main):003:0> t.try(:aoeu)
NoMethodError: undefined method `aoeu' for #<Tag id: nil, name: "!Blark!", created_at: nil, updated_at: nil>
from /usr/lib/ruby/gems/1.9.1/gems/activemodel-3.1.3/lib/active_model/attribute_methods.rb:385:in `method_missing'
from /usr/lib/ruby/gems/1.9.1/gems/activerecord-3.1.3/lib/active_record/attribute_methods.rb:60:in `method_missing'
from /usr/lib/ruby/gems/1.9.1/gems/activesupport-3.1.3/lib/active_support/core_ext/object/try.rb:32:in `try'
from (irb):3
from /usr/lib/ruby/gems/1.9.1/gems/railties-3.1.3/lib/rails/commands/console.rb:45:in `start'
from /usr/lib/ruby/gems/1.9.1/gems/railties-3.1.3/lib/rails/commands/console.rb:8:in `start'
from /usr/lib/ruby/gems/1.9.1/gems/railties-3.1.3/lib/rails/commands.rb:40:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
Tag
模型:
class Tag < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
end
推荐答案
您误解了 try
的作用.来自精美手册:
You're misunderstanding what try
does. From the fine manual:
尝试(*a, &b)
调用由符号 method
标识的方法,将任何参数和/或指定的块传递给它,就像常规的 Ruby Object#send
一样.
try(*a, &b)
Invokes the method identified by the symbolmethod
, passing it any arguments and/or the block specified, just like the regular RubyObject#send
does.
然而,与该方法不同的是,如果接收对象是 NoMethodError
异常,不会 被引发,并且 nil
将被返回code>nil 对象或 NilClass.
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.
这样做:
t.try(:aoeu)
或多或少与此相同:
t.nil?? nil : t.aoeu
但您似乎希望它表现得像这样:
but you seem to be expecting it to behave like this:
t.respond_to?(:aoeu) ? t.aoeu : nil
你的 t
不是 nil
所以 t.try(:aoeu)
和 t.aoeu
是一样的代码>.您的 Tag 类没有 aoeu
方法,因此您会得到 NoMethodError
.
Your t
isn't nil
so t.try(:aoeu)
is the same as t.aoeu
. Your Tag class doesn't have an aoeu
method so you get a NoMethodError
.
try
只是一种避免 nil
检查的便捷方法,当对象不存在时,它不是一种避免 NoMethodError
的方法不回应您尝试使用的方法.
try
is just a convenient way of avoiding a nil
check, it isn't a way to avoid a NoMethodError
when the object doesn't respond to the method you're trying to use.
这篇关于Rails 3 对象#尝试不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!