如何在模块中使用ActiveRecord?
require 'active_record'
module Module1
module Module2
class Database
ActiveRecord::Base.establish_connection(
:adapter => 'postgresql',
:host => 'db_url',
:username => 'db_username',
:password => 'db_password',
:database => 'db_name'
)
class People < ActiveRecord::Base
end
end
end
end
我可以将 ActiveRecord 建立连接位移动到初始化函数中,并实例化该类,但是,当我尝试调用 People 类时,我仍然收到 NoMethod
错误。
目标是通过执行以下操作在模块/类之外使用它:
db = Module1::Module2::Database
db.People.all.each do |Person|
puts Person
end
require 'active_record'
module Module1
module Module2
class Database
ActiveRecord::Base.establish_connection(
:adapter => 'postgresql',
:host => 'db_url',
:username => 'db_username',
:password => 'db_password',
:database => 'db_name'
)
class People < ActiveRecord::Base
end
end
end
end
I can move the ActiveRecord establish connection bit into a an initialize function, and instantiate the class however, I still get a NoMethod
error when I try to call the People class.
The goal is to use it outside of the module/class by doing something like the following:
db = Module1::Module2::Database
db.People.all.each do |Person|
puts Person
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案是移动到另一个模块中,这样它就不需要实例化,并且它不在类中:
然后使用它:
config/database.yaml
应该类似于这样:这种方法是“单线程” 从某种意义上说,您一次只能连接到一个数据库,因为当您在 ActiveRecord 连接之间切换时,它们之间的连接会相互覆盖。因此,切换获取数据并再次切换。
The answer is to move into another module so it doesn't require instantiation, and it's not in a class:
Then to use it:
config/database.yaml
should resemble this:This approach is "single threaded" in the sense that you can only be connected to one database at a time because ActiveRecord connections overwrite each other as you switch between them. So switch get your data and switch again.