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>'
The Tag model:
class Tag < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
end
You’re misunderstanding what
trydoes. From the fine manual:So doing this:
is more or less the same as this:
but you seem to be expecting it to behave like this:
Your
tisn’tnilsot.try(:aoeu)is the same ast.aoeu. Your Tag class doesn’t have anaoeumethod so you get aNoMethodError.tryis just a convenient way of avoiding anilcheck, it isn’t a way to avoid aNoMethodErrorwhen the object doesn’t respond to the method you’re trying to use.