2010-10-28 39 views
-1

为什么这是不正确的。它有什么问题?Ruby Class 500错误

#!/usr/bin/ruby 

require "mysql" 

class Game 
    attr_accessor :id, :name, :urlName, :description, :hits, :categorys, :width, :height, :nilGame 

    def load(id) 
    #Load mysql 
    begin 
     # connect to the MySQL server 
     con = Mysql.new('localhost', 'user', 'pass', 'database') 
    rescue Mysql::Error => e 
     puts "mysql error" 
     ensure 
     # disconnect from server 
     con.close if con 
    end 
    rs = con.query("select * from games where id='#{id}' limit 1") 
    rs.each_hash do |row| 
     if row['id'].nil 
     @nilGame = true 
     else 
      @id = id 
      @name = row['name'] 
      @urlName = row['urlname'] 
      @description = row['description'] 
      @hits = row['hits'] 
      @categorys = row['categorys'] 
      @width = row['width'] 
      @height = row['height'] 
     end 
    end 
    con.close 
    end 
end 
+0

500错误应始终生成详细的错误日志条目。 – 2010-10-28 09:52:32

+0

唯一的错误是在日志中不存在500错误页面:/ – Will03uk 2010-10-28 09:55:45

回答

1
  1. ensure总是被调用,不管异常升高与否。所以你试图查询一个关闭的连接。所以删除con.close确保。您可能想从return开始,因为无法查询零对象。
  2. 你可能需要require 'rubygems'在开始之前,require 'mysql'(如果作为一个独立的文件中运行)
  3. if row['id'].nil应该if row['id'].nil?
+0

谢谢你停止了错误,但它仍然返回nil为每列? – Will03uk 2010-10-28 10:16:37

+0

尝试将'puts row.inspect'作为循环中的第一条语句。你会更好地了解返回的内容。这可能是列实际上是空的。 – Swanand 2010-10-28 10:18:27

+0

我创建了3个名为id 1,2和3的类的实例,它只放一次row.inspect,然后停止。所以它没有完成页面? – Will03uk 2010-10-28 10:25:30

0

代替编码自己的MySQL适配器,尝试的ActiveRecord,DataMapper的任何其他ORM让你的生活更轻松。