DBI在ruby 1.8.7和2.1之间的行/委托行为

时间:2015-01-10 05:18:02

标签: ruby-on-rails-3.2 ruby-1.8.7 ruby-2.1 ruby-1.8

我在ruby 1.8.7中执行以下代码来读取数据库中的行:

require 'dbi'
db_conn_handle = DBI.connect("DBI:Mysql:host=localhost;database=mydb;port=3306", "root")
sth = db_conn_handle.prepare("select accounts.id, accounts.name from accounts;")
sth.execute
info = sth.to_a
puts "Info: #{info[0].class}"
info.each do |x, y|
  puts "#{x} ... #{y}"
end

从输出中可以清楚地看到,info [0] .class是DBI :: Row。使用ruby 1.8.7(rails 3.2.17)

执行此代码时效果非常好

当我尝试在ruby 2.1.5 / rails 3.2.17中执行它时,它会出现以下错误:

/home/rjain/.rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/delegate.rb:392:in `__getobj__': not delegated (ArgumentError)
    from /home/rjain/.rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/delegate.rb:341:in `block in delegating_block'
    from /home/rjain/mac/query.rb:7:in `each'
    from /home/rjain/mac/query.rb:7:in `<top (required)>'
    from /home/rjain/.rvm/gems/ruby-2.1.5/gems/railties-3.2.17/lib/rails/commands/runner.rb:52:in `eval'
    from /home/rjain/.rvm/gems/ruby-2.1.5/gems/railties-3.2.17/lib/rails/commands/runner.rb:52:in `<top (required)>'
    from /home/rjain/.rvm/gems/ruby-2.1.5/gems/railties-3.2.17/lib/rails/commands.rb:64:in `require'
    from /home/rjain/.rvm/gems/ruby-2.1.5/gems/railties-3.2.17/lib/rails/commands.rb:64:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

上面粘贴了文件/home/rjain/mac/query.rb。我想了解ruby 2.1和1.8之间导致此问题的区别。这个问题的解决方法是什么?

2 个答案:

答案 0 :(得分:5)

遇到同样的问题,追查问题。

在gem目录中找到lib / dbi / row.rb。第212行或附近应阅读

        if RUBY_VERSION =~ /^1\.9/

将其编辑为

        if RUBY_VERSION =~ /^1\.9/ || RUBY_VERSION =~ /^2/

答案 1 :(得分:2)

这也是我们使用Ruby 1.8x编写的代码时遇到的问题,当它在2.1.0中运行时,它会咳嗽起来 /usr/lib/ruby/2.1.0/delegate.rb:392:in __getobj__': not delegated (ArgumentError) from /usr/lib/ruby/2.1.0/delegate.rb:341:in阻止在delegating_block&#39;

一旦我们发现上面的jsc评论,我们就改变了dbi gem文件夹中的文件row.rb。再次,寻找部分:

 if RUBY_VERSION =~ /^1\.9/

并将其更新为

if RUBY_VERSION =~ /^1\.9/ || RUBY_VERSION =~ /^2/

之后,应用程序运行没有问题。