ruby-on-rails - Rails 3 对象#尝试不工作?

标签 ruby-on-rails ruby-on-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

最佳答案

你误会了什么try做。来自 fine manual :

try(*a, &b)
Invokes the method identified by the symbol method, passing it any arguments and/or the block specified, just like the regular Ruby Object#send does.

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

但您似乎希望它表现得像这样:
t.respond_to?(:aoeu) ? t.aoeu : nil

您的 t不是 nil所以t.try(:aoeu)t.aoeu 相同.您的标签类没有 aoeu方法所以你得到一个 NoMethodError .
try只是一种避免 nil 的便捷方法检查,这不是避免 NoMethodError 的方法当对象不响应您尝试使用的方法时。

关于ruby-on-rails - Rails 3 对象#尝试不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8697235/

相关文章:

javascript - 渲染:update do |page| tries to render template "update"

ruby-on-rails - Rspec极慢

ruby-on-rails - 我如何在此迁移中编写向下或可逆函数?

ruby-on-rails - 查找至少具有一个关联的记录,但排除任何关联都符合条件的记录

ruby-on-rails - 向 ActiveRecord 添加范围会导致层次结构错误

ruby-on-rails - 如何配置 capistrano 在一台服务器上部署 puma 和 nginx,并在另一台服务器上部署 resque?

ruby-on-rails-3 - 要求在 capistrano deploy.rb 找不到文件

ruby-on-rails - 资源和资源方法之间的区别

ruby-on-rails - 通过关系在 has_many 上使用关联值来过滤事件管理中的表(Rails 4/事件管理)

ruby-on-rails - Rails 的时间比较问题