rails try方法抛出NoMethodError?

时间:2011-09-15 06:38:51

标签: 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而不是抛出错误?

3 个答案:

答案 0 :(得分:55)

Rails 3

您从fine manual

误解了try的工作原理
  

尝试(* a,&amp; b)
  调用symbol方法标识的方法,向其传递任何参数和/或指定的块,就像常规的Ruby Object#send一样。

     

与该方法不同,如果接收对象是NoMethodError对象或nil,则不会引发nil异常,而是返回NilClass。< / p>

try that is patched into NilClass的版本:

  

<强>尝试(*参数)
  在try上拨打nil始终会返回nil

因此try不会忽略您在对象上调用不存在的方法的尝试,它会忽略您尝试在nil上调用方法并返回nil而不是提升一个例外。 try方法只是一种简单的方法,可以避免在方法调用链的每一步都检查nil


Rails 4

try的行为在Rails 4中发生了变化,现在它已经改变了:

  

调用名称作为第一个参数的公共方法,就像public_send一样,除非接收者没有响应它,调用返回nil而不是引发异常。

所以现在try立即处理这两项检查。如果您想要Rails 3行为,则有try!

  

try相同,但如果接收[sic]不是NoMethodError并且未尝试[sic]尝试的方法,则会引发nil例外。

答案 1 :(得分:8)

这就是尝试

  

调用符号方法标识的方法,并将其传递给任何方法   参数和/或指定的块,就像常规Ruby一样   对象#send会做。然而,与该方法不同,NoMethodError   如果是,则不会引发异常,而是返回nil   接收对象是零对象或NilClass。

所以,假设你在控制器中设置了@user,但是你没有实例化它,而是@user.try(:foo) => nil而不是

@user.foo
NoMethodError: undefined method `foo' for nil:NilClass

这里重点是try是一个实例方法。它还doesn't return nil if the object you try on isn't nil

答案 2 :(得分:5)

我知道这已经过时了,但它可能对其他人有所帮助,因为这是我用Google搜索此问题时出现的第一件事。我“借用”了尝试的代码并实现了我自己的 try_method 方法,该方法就像尝试一样,只是它首先检查是否在调用发送之前存在方法。我在Object中实现了它并将它放在初始化器中,现在我可以在任何对象上调用它。

class Object
  # Invokes the method identified by _method_, passing it any
  # arguments specified, just like the regular Ruby <tt>Object#send</tt> does.
  #
  # *Unlike* that method however, a +NoMethodError+ exception will *not* be raised
  # if the method does not exist.
  #
  # This differs from the regular Ruby <tt>Object#try</tt> method which only
  # suppresses the +NoMethodError+ exception if the object is Nil
  #
  # If try_method is called without a method to call, it will yield any given block with the object.
  #
  # Please also note that +try_method+ is defined on +Object+, therefore it won't work with
  # subclasses of +BasicObject+. For example, using try_method with +SimpleDelegator+ will
  # delegate +try_method+ to target instead of calling it on delegator itself.
  #
  # ==== Examples
  #
  # Without +try_method+
  #   @person && @person.respond_to?(:name) && @person.name
  # or
  #   (@person && @person.respond_to?(:name)) ? @person.name : nil
  #
  # With +try_method+
  #   @person.try_method(:name)
  #
  # +try_method+ also accepts arguments and/or a block, for the method it is trying
  #   Person.try_method(:find, 1)
  #   @people.try_method(:collect) {|p| p.name}
  #
  # Without a method argument try_method will yield to the block unless the receiver is nil.
  #   @person.try_method { |p| "#{p.first_name} #{p.last_name}" }
  #--
  # +try_method+ behaves like +Object#send+, unless called on +NilClass+ or a class that does not implement _method_.
  def try_method(method=nil, *args, &block)
    if method == nil && block_given?
      yield self
    elsif respond_to?(method)
      __send__(method, *args, &block)
    else
      nil
    end
  end
end

class NilClass
  # Calling +try_method+ on +nil+ always returns +nil+.
  # It becomes specially helpful when navigating through associations that may return +nil+.
  #
  # === Examples
  #
  #   nil.try_method(:name) # => nil
  #
  # Without +try_method+
  #   @person && @person.respond_to(:children) && !@person.children.blank? && @person.children.respond_to(:first) && @person.children.first.respond_to(:name) && @person.children.first.name
  #
  # With +try_method+
  #   @person.try_method(:children).try_method(:first).try_method(:name)
  def try_method(*args)
    nil
  end
end