Rails migration and column change - ruby-on-rails

working with sqlite3 for local dev. Prod DB is MySql.
Have a migration file for a column change.
class ChangeDateToOrders < ActiveRecord::Migration
def self.up
change_column(:orders, :closed_date, :datetime)
end
def self.down
change_column(:orders, :closed_date, :date)
end
end
Errors out saying index name 'temp_index_altered_orders_on_closed_location_id_and_parent_company_id' on table 'altered_orders' is too long; the limit is 64 characters
Know there is a limitation on index name with sqlite, but is there a workaround for this?
EDIT
Workaround I used.
class ChangeDateToOrders < ActiveRecord::Migration
def self.up
remove_index(:orders, [:closed_location_id, :parent_company_id])
change_column(:orders, :closed_date, :datetime)
add_index(:orders, [:closed_location_id, :parent_company_id], :name => "add_index_to_orders_cli_pci")
end
def self.down
remove_index(:orders, :name => "add_index_to_orders_cli_pci")
change_column(:orders, :closed_date, :date)
add_index(:orders, [:closed_location_id, :parent_company_id])
end
end

Personally, I like my production and development environments to match as much as possible. Its helps avoid gotchas. If I were deploying MySQL I would run my development environment with MySQL too. Besides, I am also not super familiar with SQLite so this approach appeals to my lazy side - I only need to know the ins and outs of one db.

You could hack your copy of active record; Add the following
opts[:name] = opts[:name][0..63] # can't be more than 64 chars long
Around line 535 (in version 3.2.9) of $GEM_HOME/gems/activerecord-3.2.9/lib/active_record/connection_adapters/sqlite_adapter.rb
It's a hack but it might get you past a hurdle. If I had more time, I'd look in to writing a test and sending a pull request to rails core team.

Related

convert hack into a proper rails migration

I have an old old app in Rails 2.3.14 I've inherited and I need to turn this SQL into a proper Rails up migration
ALTER TABLE gizmo_types ALTER gizmo_category_id SET NOT NULL
here is the original migration file
class NotNullGizmoCategoryId < ActiveRecord::Migration
def self.up
DB.execute("ALTER TABLE gizmo_types ALTER gizmo_category_id SET NOT NULL") <-- offending line
end
def self.down
end
end
This is using some sort of hack "DB.execute()" ...created by one of the former devs
...I need to turn this into a correct "Rails way" migration.
Maybe?...
change_column_null :gizmo_types, :gizmo_category_id, false"
...not sure.
What would the correct way be?

Syntax error fixing devise to not use email

class UpdateIndexOnUsers < ActiveRecord::Migration
def up
sql = 'DROP INDEX index_users_on_email'
sql << ' ON users' if Rails.env == 'production' # Heroku pg
ActiveRecord::Base.connection.execute(sql)
end
end
Getting a syntax error when trying to rake db:migrate on heroku. Any help would be greatly appreciated. Using Postgresql. I should mention it works fine locally.
Edit: The error
PG::SyntaxError: Error: syntax error at or near "ON"
Line 1: DROP INDEX index_users_on_email ON users
^
The easy thing would be to use rails' helpers and let them take care of datebase specifics:
class UpdateIndexOnUsers < ActiveRecord::Migration
def up
remove_index :users, :email
end
end
If the index was initially created with a name other than the one that rails would use by default you could do
class UpdateIndexOnUsers < ActiveRecord::Migration
def up
remove_index :users, :email, :name => 'name_of_index'
end
end
As far as I know, Postgresql doesn't support (or need) ON xxxx when dropping an index. The docs don't mention it either:
http://www.postgresql.org/docs/9.2/static/sql-dropindex.html
Just specifying the index name should be fine, though you can qualify it with the schema name which you probably don't need to do if you've got a standard setup.
If you're also using postgresql locally, then presumably it's working because ON users is only added when rails env is production whereas you're presumably running in development locally.

Rails 3 keep a single table the same across all environments

I have some data that needs to be edited online (ie cannot be a seed), but that also needs to be the same in all environments. So far the only thing i found is the has_alter_ego gem, but it does not seem to be supported anymore.
Example:
I make many changes to the default_settings table in my development database
I would like to keep only these changes transferred from my development to production database (and not the other tables which have test data)
I would rather not use a seed unless there is a way to edit seeds from the web
One option that i'm considering is having a separate database.
Anyone have a clean solution to this problem? Thanks!
How about you define a second sqlite3 database which gets checked in with your app for just this table, and use it for all three environments? For example, the sqlite3 file could be named other_db.sqlite3:
config/database.yml:
... (your other settings for dev, test, and prod databases)
other_db:
database: db/other_db.sqlite3
adapter: sqlite3
timeout: 5000
app/models/external.rb:
class External < ActiveRecord::Base
self.abstract_class = true
establish_connection :other_db
end
app/models/cross_environment_data.rb
class CrossEnvironmentData < External
...
end
In this case (though thoroughly discouraged), I would put it in a migration.
/db/migrate/_edit_data.rb
class EditData < ActiveRecord::Migration
def self.up
<Do your edits here>
end
def self.down
<undo edits here>
end
end
Then:
rake db:migrate
Now you have the same data across all environments.
For example if you wanted to append some text to the end of a chunk of text across all records of a Post.text.
script/generate migration append_text
/db/migrate/_append_text.rb
class AppendText < ActiveRecord::Migration
def self.up
Post.each{ |p| p.update_attribute(:text, "#{p.text} my additional text")}
end
def self.down
raise ActiveRecord::IrreversibleMigration
end
end
When you run:
rake db:migrate
on development, the changes will propagate accordingly and when you deploy to your other environments, you will have to run the same command and they will receive the same changes. This is more of an irreversible migration because you won't be able to validate that the data did not change since the time of migration, so make sure this is what you want to do (run it on dev) =)
NEW SOLUTION:
https://github.com/ricardochimal/taps
when you want to transfer a list of tables
$ taps push postgres://dbuser:dbpassword#localhost/dbname http://httpuser:httppassword#example.com:5000 --tables logs,tags

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
Even more shorter call
ActiveRecord::Base.connection.adapter_name == 'MySQL'
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"
There is an adapter_name in AbstractAdapter and that is there since Rails2.
So it's easier to use in the migration like this:
adapter_type = connection.adapter_name.downcase.to_sym
case adapter_type
when :mysql, :mysql2
# do the MySQL part
when :sqlite
# do the SQLite3 part
when :postgresql
# etc.
else
raise NotImplementedError, "Unknown adapter type '#{adapter_type}'"
end
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:
Loading development environment (Rails 3.0.3)
>> ActiveRecord::Base.connection.instance_of? ActiveRecord::ConnectionAdapters::MysqlAdapter
NameError: uninitialized constant ActiveRecord::ConnectionAdapters::MysqlAdapter
from (irb):1
So, I'd recommend stasl's answer and use the adapter_name property of the connection.
This might help:
execute 'alter table users modify fb_user_id bigint WHERE USER() = "mysqluser";'

Add Rows on Migrations

I'd like to know which is the preferred way to add records to a database table in a Rails Migration. I've read on Ola Bini's book (Jruby on Rails) that he does something like this:
class CreateProductCategories < ActiveRecord::Migration
#defines the AR class
class ProductType < ActiveRecord::Base; end
def self.up
#CREATE THE TABLES...
load_data
end
def self.load_data
#Use AR object to create default data
ProductType.create(:name => "type")
end
end
This is nice and clean but for some reason, doesn't work on the lasts versions of rails...
The question is, how do you populate the database with default data (like users or something)?
Thanks!
The Rails API documentation for migrations shows a simpler way to achieve this.
http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
class CreateProductCategories < ActiveRecord::Migration
def self.up
create_table "product_categories" do |t|
t.string name
# etc.
end
# Now populate the category list with default data
ProductCategory.create :name => 'Books', ...
ProductCategory.create :name => 'Games', ... # Etc.
# The "down" method takes care of the data because it
# drops the whole table.
end
def self.down
drop_table "product_categories"
end
end
Tested on Rails 2.3.0, but this should work for many earlier versions too.
You could use fixtures for that. It means having a yaml file somewhere with the data you want to insert.
Here is a changeset I committed for this in one of my app:
db/migrate/004_load_profiles.rb
require 'active_record/fixtures'
class LoadProfiles < ActiveRecord::Migration
def self.up
down()
directory = File.join(File.dirname(__FILE__), "init_data")
Fixtures.create_fixtures(directory, "profiles")
end
def self.down
Profile.delete_all
end
end
db/migrate/init_data/profiles.yaml
admin:
name: Admin
value: 1
normal:
name: Normal user
value: 2
You could also define in your seeds.rb file, for instance:
Grid.create :ref_code => 'one' , :name => 'Grade Única'
and after run:
rake db:seed
your migrations have access to all your models, so you shouldn't be creating a class inside the migration.
I am using the latest rails, and I can confirm that the example you posted definitely OUGHT to work.
However, migrations are a special beast. As long as you are clear, I don't see anything wrong with an ActiveRecord::Base.connection.execute("INSERT INTO product_types (name) VALUES ('type1'), ('type2')").
The advantage to this is, you can easily generate it by using some kind of GUI or web front-end to populate your starting data, and then doing a mysqldump -uroot database_name.product_types.
Whatever makes things easiest for the kind of person who's going to be executing your migrations and maintaining the product.
You should really not use
ProductType.create
in your migrations.
I have done similar but in the long run they are not guaranteed to work.
When you run the migration the model class you are using is the one at the time you run the migration, not the one at the time you created the migration. You will have to be sure you never change your model in such a way to stop you migration from running.
You are much better off running SQL for example:
[{name: 'Type', ..}, .. ].each do |type|
execute("INSERT INTO product_types (name) VALUES ('#{type[:name]} .. )
end

Resources