Ruby on rails 在RubyonRails3中创建通用模型时出现的问题
我正在尝试创建一个“通用模型”,这样它就可以连接到任何数据库的任何表。首先,我创建了这个类,它连接到另一个指定的数据库(不使用模式) DbRuby on rails 在RubyonRails3中创建通用模型时出现的问题,ruby-on-rails,ruby,activerecord,rails-activerecord,Ruby On Rails,Ruby,Activerecord,Rails Activerecord,我正在尝试创建一个“通用模型”,这样它就可以连接到任何数据库的任何表。首先,我创建了这个类,它连接到另一个指定的数据库(不使用模式) Db class Db < ActiveRecord::Base self.abstract_class = true attr_accessor :error def initialize(item = nil) @error = "" connect super end
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
有什么不对劲吗?有没有更好的办法?提前谢谢 为什么不简单地在运行时避免所有的麻烦
t = 'some_table'
c = Class.new(ActiveRecord::Base) { self.table_name = t }
然后,c
为某些表
引用AR类,您可以执行以下操作:
o = c.find(1)
# 'o' is now a wrapper for the row of some_table where 'id = 1'
cols = c.columns.map(&:name)
# 'cols' is now an array of some_table's column names
这是Ruby,其中类也是对象
如果需要连接到另一个数据库,则可以将建立\u连接
调用与自身表\u名称
一起放入块中:
t = 'some_table'
d = 'some_other_database'
c = Class.new(ActiveRecord::Base) do
establish_connection(:adapter => 'mysql2', :database => d, ...)
self.table_name = t
end
抽象类Db的用途是什么?您曾经是Java开发人员吗?非常感谢,太棒了!这看起来很像我可以用来解决的问题-如果您能看一下并给我一些建议,我将不胜感激。Rails 4不支持匿名ActiveRecord类:@JonathanNesbitt您有什么解决方法吗?也许使用eval或exec方法中的一种会让人不快。或者抛弃ActiveRecord,选择更灵活的方式。
t = 'some_table'
c = Class.new(ActiveRecord::Base) { self.table_name = t }
o = c.find(1)
# 'o' is now a wrapper for the row of some_table where 'id = 1'
cols = c.columns.map(&:name)
# 'cols' is now an array of some_table's column names
t = 'some_table'
d = 'some_other_database'
c = Class.new(ActiveRecord::Base) do
establish_connection(:adapter => 'mysql2', :database => d, ...)
self.table_name = t
end