Why is try throwing an error? Doesnt that defeat the whole purpose? Maybe its just in the console?
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>'
EDIT:
Thanks guys, now I get it.
Is there a way to do what I wanted without doing using respond_to?, such that User.try(:something) returns nil instead of throwing the error?
Rails 3
You misunderstand how
tryworks, from the fine manual:And the version of
trythat is patched intoNilClass:So
trydoesn’t ignore your attempt to call a non-existent method on an object, it ignores your attempt to call a method onniland returnsnilinstead of raising an exception. Thetrymethod is just an easy way to avoid having to check fornilat every step in a chain of method calls.Rails 4
The behavior of
tryhas changed in Rails 4 so now it:So now
trytakes care of both checks at once. If you want the Rails 3 behavior, there istry!: