我试图制作一个“通用模型”,以便它可以连接到任何数据库的任何表。首先,我做了这个类,它会连接到指定(不使用模式),另一个数据库在Ruby on Rails 3中制作通用模型时遇到的问题
Db的
class Db < ActiveRecord::Base
self.abstract_class = true
attr_accessor :error
def initialize(item = nil)
@error = ""
connect
super
end
def connect
could_connect = true
@error = ""
begin
ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "localhost",
:username => "root",
:password => "",
:database => "another_database",
:port => 3306,
:encoding => "utf8"
)
rescue ActiveRecord::ConnectionNotEstablished
@error = "Could not connect to database. The connection was not established"
could_connect = false
rescue Mysql2::Error
@error = "Could not connect to database using MySQL2"
could_connect = false
rescue => e
@error = "Could not connect to database. #{e.message}."
could_connect = false
end
return could_connect
end
end
于是,我做了这个类从数据库继承并指定表名
Gmodel
class Gmodel < Db
def initialize(new_table_name)
ActiveRecord::Base.set_table_name(new_table_name)
super
end
end
最后,在控制器
MainController
class MainController < ApplicationController
def index
@users = Gmodel.new("users")
end
end
但是,它gaves我这个错误:
undefined method `stringify_keys' for "users":String
出了什么问题?有没有更好的方法来做到这一点?提前致谢!
什么是抽象类DB的目的是什么? – sailor
你曾经是一名Java开发人员吗? –