New to Rails here. Couple of questions about migrations:
I created a migration that I no longer want. I want to remove it. Is the correct command simply rails destroy migration AddMyColumnToMyModel ?
Let's say I mistype that migration name that I want to destroy... Here's what happens when I attempt to destroy a migration that does not exist.
$ rails destroy migration Blah
invoke active_record
remove migration.rb
It says it's removing migration.rb... Is this a bad thing?
Sure, that's the right command. Just be careful: if you actually ran the unwanted migration by using rake db:migrate to commit the changes to your database, be sure to run this before anything else:
rake db:rollback
What that does is run the down method on your latest migration. It does absolutely the same thing as:
rake db:migrate:down VERSION=20130529014413
Where the version number corresponds to that of your latest migration. It can also take a STEP parameter in case you need to roll back a bunch of migrations instead of only one, like so:
rake db:rollback STEP=3
Of course, if you just generated your unwanted migration and never ran it, there's no need to roll anything back. You can use the command you posted or manually delete the corresponding file to get rid of it.
Source: http://guides.rubyonrails.org/migrations.html#rolling-back
Don't worry, that's not doing anything to your code.
Related
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 have different migrations file
20120205111326_change_users_login_limit.rb
20120223110929_change_attachments_container_defaults.rb
20120223110300_change_locals_container_defaults.rb
20120223110301_change_position_tracs.rb
I want to run up migration of 20120205111326, 20120223110929, 20120223110300 just before the last migration but condition is that it should not point its migration VERSION numbers...
Is there any ways to do it...please suggest me..
Thank you in advance
There is one way, Run your migration via rails console
require "db/migrate/20120205111326_change_users_login_limit.rb"
ChangeUsersLoginLimit.change # or 'up' or 'down' whatever method of that migration you want to run.
And do the same for all migration (don't forget to do it in sequence)
EDIT:
Rails actually don't provide a way to run migration skipping some. or run them by changing order. But the migration files are actually a ruby programs containing a single class. So you can always create a rake task and require migration in to rake task and run them in the custom logical order. After all migrations are the classes with methods.
When I ran bundle exec rake db:test:prepare I got the following:
rake aborted!
Multiple migrations have the name CreateMicroposts
To check the status of my migration files, I ran
rake db:migrate:status
And got:
Status Migration ID Migration Name
------- --------------- -----------------
up 20120616205407 Create users
up 20120622103932 Add index to users email
up 20120622114559 Add password digest to users
up 20120628095820 Add remember token to users
up 20120704123654 Add admin to users
down 20120706103254 Create microposts
up 20120707073410 Create microposts
As you can see, I have two migration files with the exact same names and the exact same code in them. It's only their statuses differ, i.e. Up and Down.
What does Up and Down signify?
And which one can I delete, if I have to?
The problem is that you have two different migration files containing the header
class CreateMicroposts< ActiveRecord::Migration
rake db:migrate:status does not check the status of your migration files. It tells you what migrations will be applied if you run rake db:migrate. The up/down labels are pretty much self-explanatory: it tells you whether the migration will be applied via the up method or the down method. The up method is ran when you migrate and the down when you rollback a migration. You can make some further reading about Rails migrations here.
up is the method called when "evolving" (ie migrating to a new schema), while down is the method called when "regressing" (ie migrating to an older schema version, because one of your changes doesn't suit you). db:migrate calls up, db:rollback calls down. In recent versions of rails, there's change that handles both at the same time.
As for the deletion... I don't do activerecord much these days, but I think you're free to do whatever you want with your files. I don't think deleting a duplicate file will do any harm, and if it does.. Well, you use source control, right ? :)
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 have a table that I created using the migrations, now I want to get rid of this table. I'm pretty sure I can just back out that migration, but I can't find the syntax to do that. I found this question from searching Rails DB Migration - How To Drop a Table?
but he basically says you can find what you need and provides a link. I read that link and I didn't see anything that says how to do it. I saw pieces of it, but I don't know how to put them together.
I see in the migration it has a self.down method, I really just need to know how to call that.
Try to create an empty migration and use:
drop_table :table_name
You can rollback the last migration with:
rake db:rollback
That will run the self.down method, which should be drop_table :table_name
rake db:rollback STEP=n
where n is the number of steps you need to roll back. If you leave the STEP off it just rolls back 1.
To migrate to a particular version, use:
rake db:migrate:down VERSION=20080906120000
If you want to quickly apply a table drop, you could create a new migration, run it, then delete it along with the original migration you no longer want. The syntax for dropping a table is:
drop_table :table_name
Destroying the model is not the best way.
Instead, run this command in your rails console: rake db:rollback
(to access the rails console, type rails c in a terminal as shown here)
You can remove a table using rake to destroy the model:
rails destroy model your_model