rails migration version issue: any new migration not working - ruby-on-rails

From this morning, I am facing weird issues with Rails devise. Following is output of my ls and rake db version command.
hrishikesh#hrishikesh-ubuntu:~/git-public/personaldiary/db/migrate$ ls -1
20120110083934_devise_create_users.rb
20120110090514_create_posts.rb
20120110090845_add_user_id_to_post.rb
20120203035323_add_confirmable_to_devise.rb
20120203035323_add_confirmable_to_devise.rb~
20120203043601_add_lockable_to_devise.rb
20120203043601_add_lockable_to_devise.rb~
hrishikesh#hrishikesh-ubuntu:~/git-public/personaldiary/db/migrate$ rake db:version
(in /home/hrishikesh/git-public/personaldiary)
DEPRECATION WARNING: require "activerecord" is deprecated and will be removed in Rails 3. Use require "active_record" instead. (called from /usr/lib/ruby/vendor_ruby/activerecord.rb:2)
Current version: 20120203034555
hrishikesh#hrishikesh-ubuntu:~/git-public/personaldiary/db/migrate$
If I try to add any new migrations, rake db:migrate throws error that tells me that some column already exists, and fails.
My failing migration code is here:
class AddConfirmableToDevise < ActiveRecord::Migration
def change
change_table(:users) do |t|
t.confirmable
end
add_index :users, :confirmation_token, :unique => true
end
end
I specifically do not want to use up and down methods because of this
Please help.

After spending hours to find solution, I decided to give up and ran
rake db:migrate:reset
And it worked, only thing is my data was lost, which was not that big deal at this point.
Thank you everyone for attempting to solve this.

Related

Trouble adding st_point column with activerecord-postgis-adapter

This is a pretty verbatim copy of what I wrote on the project github. Forgive me for cross posting but I was hoping someone here had come across this error:
undefined method `st_point' for #
<ActiveRecord::ConnectionAdapters::PostgreSQL::TableDefinition:0x0055cdd8f278e8>
This is my Gemfile lock:
activerecord (4.2.7.1)
activerecord-postgis-adapter (3.1.4)
and the migration:
class CreateLocations < ActiveRecord::Migration
def change
enable_extension "postgis"
create_table :locations do |t|
t.st_point :geom, geographic: true, srid: 4326, dimension: 2
t.timestamps
end
end
end
What's wierd is that this works in development mode. It's just when I run the migrations for the test environment that it fails.
After rake db:create RAILS_ENV=test, I have conntected to the test database with psql and run CREATE EXTENSION postgis;.
tl;dr
t.st_point in the migration is undefined, only in the test environment.
The error was "postgres" instead of "postgis" in the ENV["DATABASE_URL"]
That it what others suggested on the thread. I was being stubborn by not checking for this, but it turns out to be the correct cause.

What to do after a failed heroku db:rollback

I'm at the very beginning stages of learning rails using heroku as deployment tool. I ran into a bit of problem today, which is now fixed, but I was wondering if there's a proper/better way to do what I did.
My problem was as follows: I wrote a migration file that created a table with some indices (using add_index). The code would look like this:
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
t.string :username
...
end
add_index :users, :username, :unique => true
end
def self.down
drop_table(:users)
remove_index :users, :username
end
end
heroku run rake db:migrate ran fine but heroku run rake db:rollback failed because (I assume) remove_index was trying to delete an index from a column that had already been erased.
So I then added a self.down method to my migration file (removing the indices before dropping the table). Afterwards, heroku run rake db:migrate didn't do anything, and heroku run rake db:rollback is stuck at the same error as before. Resetting the database or dropping the table didn't work either. I ended up removing the add_index lines in my migration before the rollback finally works.
... and unfortunately I no longer have any idea why db:rollback failed. The error message was 'index_users_on_username' on table 'users' does not exist', so my guess is that I did something stupid like modifying the database or modified the migration file before doing a rollback. Or could it be because I am mixing change and down method in the same migration file?
Anyway, my main question is, if a db:rollback fails, what then?
Some options in my head:
Fix the migration file until the rollback works
Fix the database manually until the rollback works
Fix the database manually and ignore the migration completely (dunno how to do this)
this)
???

Why am I getting a method undefined error in rails?

I'm working on letting users sign in and out of my rails app. The error I get is as follows
undefined method 'find_by_remember_token'
The method in question is written like this:
def current_user
#current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
Any help you can provide in fixing this error would be greatly appreciated!
you can reset your database and migrate in one line:
rake db:migrate:reset && rake db:migrate && annotate
use the gem annotate in your project to have a better view of your database columns
in your Gemfile add:
gem 'annotate'
and in console run:
bundle update && bundle install
You don't have a field in your users table called remember_token ?
I know this is an old question, but I had the same problem and wanted to include how I fixed it.
First, I made sure I added the required info to the migration:
class AddRememberTokenToUsers < ActiveRecord::Migration
def change
add_column :users, :remember_token, :string
add_index :users, :remember_token
end
end
then I just dumped my db and remigrated:
rake db:drop
rake db:create
rake db:migrate
worked for me after that.

Ruby on Rails: How can I revert a migration with rake db:migrate?

After installing devise MODEL User i got this.
class DeviseCreateUsers < ActiveRecord::Migration
def self.up
create_table(:users) do |t|
t.database_authenticatable :null => false
t.recoverable
t.rememberable
t.trackable
# t.encryptable
# t.confirmable
# t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both
# t.token_authenticatable
t.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :reset_password_token, :unique => true
# add_index :users, :confirmation_token, :unique => true
# add_index :users, :unlock_token, :unique => true
# add_index :users, :authentication_token, :unique => true
end
def self.down
drop_table :users
end
end
Now if i do rake db:migrate the users table will be created.
How can i revert this migration, i.e. how can I delete the users table using rake again ?
Run the following command
rake db:migrate:down VERSION=<version>
where <version> is the version number of your migration file you want to revert.
eg. if you want to revert a migration with file name 3846656238_create_users.rb
rake db:migrate:down VERSION=3846656238
Just run this command:
rake db:rollback
I believe there are three options available for reverting migrations (they also overlap):
Roll down the most recent migration:
rake db:migrate:down # Rails 2 only.
Roll down a number(n) of recent migrations:
rake db:rollback STEP=n
Roll down to a previous, specific version:
$ rake db:migrate:down VERSION=nnn # Rails 3 (provide version number also).
Version Number means the SHA(Secure Hash Algorithm) for the commit which is a long hexadecimal number which looks something like 886af3194768917c78e... You can see it by doing git log
You can see these commands (and others) with their descriptions by using rake -T db: which for rails 3.2 includes:
rake db:migrate # Migrate the database (options: VERSION=x, VERBOSE=false)
rake db:migrate:status # Display status of migrations
rake db:rollback # Rolls the schema back to the previous version (specify steps w/ STEP=n)
You can do rollback and specify how many last migrations will be rollbacked, e.g.
rake db:rollback STEP=3
for 3 last migrations.
As an new programmer (or to other new programmers)
rake db:rollback works about half the time. I start there.
If not, rake db:migrate:down VERSION=3846656238
plug in VERSION for the version number of your migration file you want to revert.
rake db:migrate:redo
It will undo and reapply the last migration.
For rails 5 we can use rails command instead of rake
rails db:migrate:down VERSION=<version>
example
rails db:migrate:down VERSION=20170330090327
Run this command in your terminal:
rake db:migrate:status
or
bundle exec rake db:migrate:status
It shows the status, migration ID's, migration name for all migration we ran previously. select your migration id (i.e your version number) and put that id in the following command after version= ,,, and press enter
bundle exec rake db:migrate:down VERSION=
How to Roll back a migration
Another way. I prefer this because you need to be explicit, rather than rolling back - just in case you might make a mistake.
(1) First Identify The Migration ID
rake db:migrate:status
Copy the ID number.
(2) Then Roll back the migration
rake db:migrate:down VERSION=20190802023239
Paste the relevant ID number above. Of course, in your case, the migration ID will be different!
.......and now you're off to the races!

Run migrations from rails console

Is there a way to run rake commands for db:migrate and db:rollback on the console?
It sucks to wait for the rails environment to load!
In the console:
ActiveRecord::Migration.remove_column :table_name, :column_name
To update your schema.rb file after running migrations from the console, you must run rails db:migrate
Rails <= 4
This will allow you to migrate without reloading the whole rails environment:
ActiveRecord::Migrator.migrate "db/migrate"
and rollback:
# 3 is the number of migration to rollback, optional, defaults to 1
ActiveRecord::Migrator.rollback "db/migrate", 3
Rails >= 5 (thanks to #gssbzn, his answer is below)
Migrate :
ActiveRecord::MigrationContext.new("db/migrate").migrate
And rollback :
# 3 is the number of migration to rollback, optional, defaults to 1
ActiveRecord::MigrationContext.new("db/migrate").rollback 3
Another way that I find neater to just run some migration command from console is this:
ActiveRecord::Schema.define do
create_table :foo do |t|
t.string :bar
t.timestamps
end
end
This has the advantage that the contents inside the block is compatible with just copy and pasting random contents from a real migration file / schema.rb.
For rails 5.2 the accepted answer has been removed and replaced with
ActiveRecord::MigrationContext.new("db/migrate").migrate
Please be aware as this may also change for future versions of rails as they work to add multiple database connections
For Rails 5 and Rails 6:
ActiveRecord::Base.connection.migration_context.migrate
For Rails 3 and Rails 4:
ActiveRecord::Migrator.migrate 'db/migrate'
I needed to pretend a migration was run to unblock a deploy, this can be done with:
class Mig < ActiveRecord::Base; self.table_name = 'schema_migrations';end
Mig.create! version: '20180611172637'
You can use the %x[command]
%x[rake db:migrate]
To run single migration
ActiveRecord::Migration.add_column(:table_name, :column_name, :data_type)
To run all migrations
ActiveRecord::Migrator.migrate('db/migrate')
To rollback n migrations
ActiveRecord::Migrator.rollback('db/migrate', n)
I created a method in my .irbrc file that runs migrations then reloads the console:
def migrate
if defined? Rails::Console # turn off info logging for Rails 3
old_log_level = ActiveRecord::Base.logger.try(:sev_threshold)
ActiveRecord::Base.logger.sev_threshold = Logger::WARN
end
reload! && migations_ran = true if ActiveRecord::Migrator.migrate(Rails.root.join("db/migrate")).any?
ActiveRecord::Base.logger.sev_threshold = old_log_level if defined? old_log_level
migations_ran ||= nil # useful exit status
end
See the entire file here: https://gist.github.com/imme5150/6548368

Resources