I'm trying to update my heroku database. The problem: I created an old model & table that we no longer need. That table had previously been migrated to a production server (along with other changes). I did a destroy of the model using:
rails destroy model ReallyLongModelName
That also deleted the migration that created the table.
Later, I created a migration to drop that table.
class Drop_ReallyLongTableName < ActiveRecord::Migration
def change
drop_table :really_long_table_name
end
end
I'm now getting a couple of errors.
First error:
When trying to migrate the database to the production version of the application, I get this error.
Input string is longer than NAMEDATALEN-1 (63)
I'm not sure how to go back and edit the name to avoid the long name, so that it clears
Second error:
When trying to rollback the Drop_ReallyLongTableName migration, its aborts the rake because
rake aborted!
An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: no such table: really_long_table_name
Does anyone have any ideas on how to solve this? Thanks!
Have you tried running this from your Terminal/console:
heroku run console
ActiveRecord::Migration.drop_table(:table_name)
The migration is the way to go but this might be worth a try to see if the table even exists any more (since your second error message seems to indicate that it is no longer there).
Also, and for what it's worth, you can add conditional logic to your DB migrations should you need to in the future
def change
drop_table :table_name if self.table_exists?("table_name")
end
Related
This is the error I get when running a migration in a RoR application:
PG::Error: ERROR: column "bulk_bill" of relation "questionnaires" already exists
A little background:
I rolled back a migration so that I could change the default setting for a column.
Once I ran the migration again I got the error above.
I can see in the postgresql table in development that the column does exist. I have a data in the tables and in the bulk_bill column it has it's default set to false.
What are the recommended steps I need to take so that I so the migration can be run successfully.
I am a beginner in ruby and find the ruby documentation still a little hard to follow.
def up
add_column :questionnaires, :bulk_bill, :boolean, :default => false
end
def down
remove_column :pnp_questionnaires, :bulk_bill
end
In your up method you're creating column on questionaries table, and in your down method you are removing it from pnp_questionaries. Remove column does not raise an excepton if table doesn't exists, hence you have your problem.
Simplest solution:
Comment out add_column from up.
Run migrations (yes, run empty migration).
Fix your down method to remove questionaries table.
Rollback migration.
Uncomment your up method.
UPDATE:
My bad - point 3 was to be 'remove column from questionaries', not 'remove table'.
You need to rerun the migration which created the table (hopefuly you didn't alter it in a meantime). Go to the given migration, comment out down method body, and run rake db:migrate:redo VERSION=xxxxxxx where xxxxxx is the timestamp in this migration filename.
The problem is the following:
I have db/seed.rb full of initial data.
One of migrations depends on data this seed provides.
I'm trying to deploy my app from empty db.
Result is:
RAILS_ENV=production rake db:migrate - fails due to lack of initial data
RAILS_ENV=production rake db:seed - fails due to pending migrations
I wanted to somehow tell rake to ignore pending migrations, but unable to do it so far.
UPDATE (due to additional experience)
Sometimes migrations and model code goes out of sync, so migrations are not being run.
To avoid this problem recently used redefining of model in migrations:
# reset all callbacks, hooks, etc for this model
class MyAwesomeModel < ActiveRecord::Base
end
class DoSomethingCool < ActiveRecord::Migration
def change
...
end
end
I am not very sure if this will help you. But I was looking for something and found this question. So it looks like this might help:
In RAILS_ROOT/config/environments/development.rb
Set the following setting to false:
# NOTE: original version is `:page_load`
config.active_record.migration_error = false
In my situation it now does not show the pending migration error anymore. Should work for rake tasks and console for the same environment as well.
Source in rails/rails
Rename the migration dependent on the data from:
20140730091353_migration_name.rb
to
.20140730091353_migration_name.rb
(add a dot at the start of the filename)
Then run rake db:seed (it will no longer complain on the pending migrations) and then rename back the migration.
If you have more migrations following after, you have to rename all of them or just move it temporary away.
Rails stores migration information in a table called schema_migrations.
You can add the version from your migration into that table to skip a specific migration.
The version is the number string which comes before the description in the file name.
[version]_Create_Awesome.rb
I had a similar issue. I commented out the add_column lines and ran the rake db:migrate commands and then removed the comment when I will need it for the testing or production environment.
There is no way unless you monkey patch the Rails code. I strongly advise you to fix your migrations instead.
A migration should not depend on the existence of some data in the database. It can depend on a previous migration, but of course absolutely not on the data on the db.
If you came across the "pending migrations" issue when trying to seed your data from within a running Rails application, you can simply call this directly which avoids the abort_if_pending_migrations check:
ActiveRecord::Tasks::DatabaseTasks.load_seed
See where seeds are actually called from within ActiveRecord:
https://github.com/rails/rails/blob/v6.0.3.2/activerecord/lib/active_record/railties/databases.rake#L331
and see the DatabaseTasks docs:
https://apidock.com/rails/v6.0.0/ActiveRecord/Tasks/DatabaseTasks
https://apidock.com/rails/v6.0.0/ActiveRecord/Tasks/DatabaseTasks/load_seed
I'm an idiot...screwed up a migration in Rails:
thinking migrations would work like model generators (using references:modelname) I did the following:
$ rails g migration add_event_to_photos references:event
which created the migration
class AddEventToPhotos < ActiveRecord::Migration
def change
add_column :photos, :references, :event
end
end
And now my development database (SQLite3) has a references column of type event in the photos table.
And my schema.rb has a line in the middle saying:
# Could not dump table "photos" because of following StandardError
# Unknown type 'event' for column 'references'
rake db:rollback is powerless against this:
$ rake db:rollback
== AddEventToPhotos: reverting ===============================================
-- remove_column("photos", :references)
rake aborted!
An error has occurred, this and all later migrations canceled:
undefined method `to_sym' for nil:NilClass
So, how to roll back and maintain my development data in the database? I'd even be happy trashing the photos table if that's my only choice..but don't want to have to rebuild the whole thing. What to do?
btw- for anyone reading this about to make same stupid mistake...don't! Use the correct migration generator:
$ rails g migration add_event_to_photos event_id:integer
The easiest way I found to do this was to recreate the table in the schema.rb file in /db/. Afterwards I ran a rake db:reset (if it says you have pending migrations, just delete them and try again).
This took care of the problem.
Go into the database by ./script/rails dbconsole. Then type these commands:
.output dump.sql
.dump
In the file dump.sql you will have the SQL commands used to recreate and populate your database. Just edit it with your favourite editor (like vim ;-) removing or fixing the column type. You may also remove the invalid migration identifier from the schema_migrations table. Drop your database (I suggest just rename the db/development.sqlite file), create new database and read the dump file into it (using command .read dump.sql).
Now you just need to fix and run your migrations.
add an empty down method and run rake db:rollback
edit ahh that's the new migration syntax, you can replace the body with simply:
def self.down; end
which is the old syntax, or perhaps delete the body altogether (haven't tried this) and then run rake db:rollback
Just an idea, I know it's not SQLite specific you can revert to an older version schema perhaps, load it up. And try again from there? You can revert (checkout) specific files in GIT. And then do def self.down; end, as was suggested by another poster.
The problem arises because while SQLite will create the schema with whatever type you give it (in this case event it can't dump that type back to ActiveRecord.
You need to edit the sqlite_master file and change create table string (sql) to be the right thing.
You probably want to back up your table first since messing up that string will wreck your table if you do it wrong.
Here is a related rails issue
I am using Ruby on Rails and I no longer need my table Order so I deleted it using SQLite manager.. How can I make the table deletion take place in heroku?
EDIT
I am getting the error
db/migrate/20110806052256_droptableorders.rb:10: syntax error, unexpected keyword_end, expecting $end
When i run the command
class DropTableOrder < ActiveRecord::Migration
self.up
drop_table :orders
end
self.down
raise IrreversibleMigration
end
end
In case you don't want to create a migration to drop table and cant rollback the previous migrations because you don't want to lose the data in the tables created after that migration, you could use following commands on heroku console to drop a table:
$ heroku console
Ruby console for heroku-project-name
>> ActiveRecord::Migration.drop_table(:orders)
Above command will drop the table from your heroku database. You can use other methods like create_table, add_column, add_index etc. in the ActiveRecord::Migration module to manipulate database without creating and running a migration. But be warned that this will leave a mess behind in the schema_migrations table created by Rails for managing migration versions.
This could only be useful if your application is still under development and you don't want to lose the data you have added on remote staging server on heroku.
Execute following command.Here 'abc' is app name
heroku run console --app abc
Then use,
ActiveRecord::Migration.drop_table(:orders)
It will drop the table 'order'.
Just create a migration like this:
def self.up
drop_table :orders
end
def self.down
# whatever you need to recreate the table or
# raise IrreversibleMigration
# if you want this to be irreversible.
end
and then do a heroku rake db:migrate the next time you push your changes.
You might want to recreate the table in SQLite so that you can run this migration locally as well.
I'm fairly new to Ruby on Rails here.
I have 2 migrate files that were provided. The first one, prefixed with 001, creates a table and some columns for that table. The next migrate file, prefixed with 002, inserts rows into the table created in file 001.
Running the migration (rake db:migrate in command line) correctly creates the table but doesn't insert any of the data which is the problem. The code from the insertion looks like this (except with a lot more Student.create statements,
class AddStudentData < ActiveRecord::Migration
def self.up
...
Student.create(:name => "Yhi, Manfredo", :gender => "M")
...
end
def self.down
Student.delete_all
end
end
My understanding is that Student is a model object, so my Student model looks like this,
class Student < ActiveRecord::Base
end
Do I need to explicitly define a create method in Student or is that something that's given? (This project was made using scaffold)
Thanks.
Edit 1: I used Damien's suggestion and called create! instead of create but got the same response. Then what I did to see whether the code was even reaching that far was call this,
Student.create12312313!(:name => "foo", :gender => "M")
which is obviously invalid code and the migrate didn't throw any error.
Edit2: Answer found. The schema_migrations table had its version set to 3, and I only had 3 different migration files so it never ran any of the migration files I had. That's why nothing was ever updating, and the bogus creates I used were never throwing errors. The reason the student data wasn't inserted the first time was because a certain table was already in the database and it caused a conflict the first time I migrated. So what I was really looking for wasn't db:migrate but rather db:reset Several hours well spent.
The create method is inherited from ActiveRecord::Base.
So no, you don't need to define it.
One reason why your datas could not be included would be that you have validations that doesn't pass.
You can easily see the error making your datas not being included by using create! instead of create.
So if the model can't be created, an exception will be thrown and the migrations will fail.
You may want to look at Data Seeding in rails 2.3.4. And is your rails migrations really running 001_create_whatever.rb? or were you just using that as an example? since 2.2.2 (iirc) migrations have been using timestamps such as 10092009....create_whatever.rb
How old is your rails version?
The migrations won't run if their schema number is in the database.
For older versions of rails, there will be a single row with the highest migration performed in it.
For newer versions, every migration gets a unique time-stamp as its version number, and its own row in schema_migrations when it gets added.