2012-01-02 36 views
3

我應該從哪裏開始尋找?這裏是什麼讓我相信:Rails 3對象#請嘗試不工作?

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 

回答

19

你誤會什麼try一樣。從fine manual

嘗試(*一,& B)
調用由符號method標識的方法,傳遞的任何參數和/或指定的塊,就像常規的Ruby Object#send一樣。

不同於然而該方法中,一個NoMethodError異常將被升高和nil將被代替返回,如果接收的對象是對象nil或NilClass。

所以這樣做:

t.try(:aoeu) 

或多或少與此相同:

t.nil?? nil : t.aoeu 

但你似乎在期待它的表現是這樣的:

t.respond_to?(:aoeu) ? t.aoeu : nil 

您的t不是nil所以t.try(:aoeu)t.aoeu相同。你的標籤類沒有aoeu方法,所以你得到一個NoMethodError

try只是一種避免nil檢查的便捷方式,當對象不響應您嘗試使用的方法時,它不是一種避免NoMethodError的方法。

+0

謝謝。 。 。 。 。 – 2012-01-02 04:08:08