Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check the Database type in a Rails Migration?

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 
like image 863
Shaun Avatar asked Oct 27 '09 03:10

Shaun


People also ask

How do I view a Rails database?

You can use rails dbconsole to view the database that your rails application is using. It's alternative answer rails db . Both commands will direct you the command line interface and will allow you to use that database query syntax.

How can I check my Rails migration status?

rake db:migrate:status (Rails 3 to 5) or rails db:migrate:status (Rails 5) will accomplish this. See this commit. up means the migration has been run. down means the migration has not been run.

What is database migration in Rails?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.

Where is the database stored in Rails?

By default, Rails uses SQLite3. The database files are stored in the /db directory in the root of your app. There should be a file called development.


2 Answers

Even more shorter call

ActiveRecord::Base.connection.adapter_name == 'MySQL' 
like image 58
stasl Avatar answered Oct 14 '22 10:10

stasl


ActiveRecord::Base.connection will provide you with everything you ever wanted to know about the database connection established by boot.rb and environment.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:

ActiveRecord::Base.connection.instance_of?    ActiveRecord::ConnectionAdapters::MysqlAdapter  

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:

ActiveRecord::Base.connection.instance_values["config"][:adapter] == "mysql" 
like image 20
EmFi Avatar answered Oct 14 '22 10:10

EmFi