如何检查 Rails 迁移中的数据库类型?
我有以下迁移,我希望能够检查当前与环境相关的数据库是否是mysql数据库。如果是mysql,那么我想执行特定于数据库的SQL。
我该怎么办?
class AddUsersFb < ActiveRecord::Migration def self.up add_column :users, :fb_user_id, :integer add_column :users, :email_hash, :string #if mysql #execute("alter table users modify fb_user_id bigint") end def self.down remove_column :users, :fb_user_id remove_column :users, :email_hash end end
I have the following migration and I want to be able to check if the current database related to the environment is a mysql database. If it's mysql then I want to execute the SQL that is specific to the database.
How do I go about this?
class AddUsersFb < ActiveRecord::Migration def self.up add_column :users, :fb_user_id, :integer add_column :users, :email_hash, :string #if mysql #execute("alter table users modify fb_user_id bigint") end def self.down remove_column :users, :fb_user_id remove_column :users, :email_hash end end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
更短的通话
Even more shorter call
ActiveRecord::Base.connection
将为您提供有关由boot.rb
和environment.rb
建立的数据库连接的所有信息ActiveRecord::Base.connection
返回大量信息。所以你必须确切地知道你在寻找什么。正如 Marcel 指出的:
可能是确定您的数据库是否为 MySQL 的最佳方法。
尽管依赖的内部信息可能会在
ActiveRecord
版本之间发生变化,但我更喜欢这样做:ActiveRecord::Base.connection
will provide you with everything you ever wanted to know about the database connection established byboot.rb
andenvironment.rb
ActiveRecord::Base.connection
returns a lot of information. So you've got to know exactly what you're looking for.As Marcel points out:
is probably the best method of determining if your database MySQL.
Despite relying on internal information that could change between
ActiveRecord
release, I prefer doing it this way:有一个
adapter_name
< /a> 在AbstractAdapter
中从 Rails2 开始就存在了。因此在迁移中使用起来更容易,如下所示:
There is an
adapter_name
inAbstractAdapter
and that is there since Rails2.So it's easier to use in the migration like this:
在 Rails 3 中(也许更早,但我目前正在使用 Rails 3),使用 ActiveRecord::ConnectionAdapters::MysqlAdapter 是一个糟糕的方法,因为它仅在使用的数据库适配器是 MySQL 时才进行初始化。即使您安装了 MySQL gem,如果它不是您的连接类型,该调用也会失败:
因此,我建议 stasl 的答案并使用连接的adapter_name 属性。
In Rails 3, (maybe earlier, but I'm using Rails 3 currently) using ActiveRecord::ConnectionAdapters::MysqlAdapter is a poor way to go about it, as it's only initialized if the database adapter in use is MySQL. Even if you have the MySQL gem installed, if it's not your connection type, that call wil fail:
So, I'd recommend stasl's answer and use the adapter_name property of the connection.
这可能会有所帮助:
执行'alter table users修改fb_user_id bigint WHERE USER() = "mysqluser";'
This might help:
execute 'alter table users modify fb_user_id bigint WHERE USER() = "mysqluser";'