Rails error resolving - ruby-on-rails

I want to overwrite the existing users table in the database. I have manually deleted the migration file user.rb and model file. After that when I type rails g model User email:string password:string
it creates the above files again but when I run the rake db:migrate command it just gives me the following error:
rake db:migrate
== 20150413203600 CreateUsers: migrating ======================================
-- create_table(:users)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "users" already exists: CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "email" varchar(255), "password" varchar(255), "created_at" dateti
me, "updated_at" datetime) /home/action/.gem/ruby/2.1.1/gems/sqlite3-1.3.10/lib/sqlite3/database.rb:91:in `initialize'

If you open up your db/schema.rb file, you will see that you already have a users table. Deleting the migration file doesn't do anything besides not running the migration file if you were to run rake db:migrate on another computer. Run rake db:rollback will delete the last thing that you rake db:migrate, then generate your new user migration along with rake db:migrate.

You should not have deleted the migration file, as rails would have used the migration file under a rake db:rollback command to delete the users table for you.
If you don't mind losing ALL your tables, and since you're using SQLite3, you can look in your db folder for a file called development.sqlite3 and possibly test.sqlite3. Delete those and you no longer have any database tables at all and you can run migrations to re-create them.
If you ONLY want to drop the users table, delete the migrations that you've recently generated to "create user table" and then create a migration rails g migration DropUsersTable then modify it to look like the following
class DropUsersTable < ActiveRecord::Migration
def change
drop_table :users
end
end
Run migration and that will drop your existing users table. Then, you should delete the migration file. As I said, it's not good practice to delete migration files but in this case since you've destroyed the migration that created the original user table, you should destroy the migration that dropped that table.
At this point, you have no migrations that reference users table and you have no users table so you can now generate the migration to create it and this time it should work.
If you change your mind and you want to drop the users table again, remember, DO NOT delete the migration file, just do rake db:rollback then adjust the migration file to create the table as you'd like it and then run rake db:migrate again.

Related

Rails error in migration ActiveModel::UnknownAttributeError: unknown attribute

I want to remove column and index in activities table. To do so I've got below migration:
class RemoveUnnecessaryJourneyActivitiesRelations < ActiveRecord::Migration[6.0]
def change
remove_index :activities, :cms_journey_id
remove_column :activities, :cms_journey_id, :bigint
end
end
When I run rake db:migrate it removes this column and index as well but when I want to reset my DB by rake db:drop db:create db:migrate db:seed or bin/rails db:setup I'm getting an error:
rake aborted!
ActiveModel::UnknownAttributeError: unknown attribute 'cms_journey_id' for Activity.
How was the attribute added in the first place? If it was via a migration it looks like that file had been deleted.
You have two options - if you want to get the above migration working, you'll need to insert one before it (with an earlier timestamp) that creates the attribute, and then run this migration to remove it.
Of course, the easier option is to just delete the above migration. Because there is no migration that creates the attribute, you can delete the above migration, run rake db:migrate, have a look at your db.schema.rb file, and you'll see no column called cms_journey_id on the activities table.

Fixing migration error

I tried to create a migration to add roles to my user tables but i accidentally typed AddRolesToUsers instead of AddRoleToUser. So i tried creating a new migration with the correct AddRoleToUsers but when i tried to run rake db:migrate i got an error :
SQLite3::SQLException: duplicate column name: role: ALTER TABLE "users" ADD "role" integer/Users/miguel/.rvm/gems/ruby-2.2.1/gems/sqlite3-1.3.11/lib/sqlite3/database.rb:91:in `initialize'
I tried rake db:migrate:down VERSION= do delete the one I had to type on but i keep getting the same error . PS: i deleted the migration file manually after running rake db:migrate:down VERSION=
rails g migration AddRoleToUsers role:integer
migration file :
class AddRoleToUsers < ActiveRecord::Migration
def change
add_column :users, :role, :integer
end
end
When you ran the first migration, the role column was added to the Users table. The error on the second migration tells you that much.
To clear the migration pending error, you need to comment out the add_column statement in the new migration.
i.e,
class AddRoleToUsers < ActiveRecord::Migration
def change
# add_column :users, :role, :integer
end
end
Then run the migration. This way, the new migration should run successfully.
You can now uncomment it and delete the previous migration, so that when you deploy, only the newer migration is run and the role column is added successfully.
In that case right click and delete both migration files and start again. The error exists because it thinks you want to add two columns both named role to your users table
UPDATE
In that case, if role already exists in your users table, a migration must've been successfully run and there is no need to run another. As long as the role column is there, trying to add another column called role will always give you an error. If you wanted to test that you are still able to add new columns you can always check by creating a test migration AddSomethingToUsers something:string and rake db:migrate to test, then rake db:rollback to undo..but it all seems like it's worked so I probably my wouldn't mess with it too much.

Remove column from postgresql via rails

I use this command to create an avatar column in my postgresql database.
rails g migration add_avatar_to_users avatar:string
rake db:migrate
I have an image column i would like to get rid of in the same database. I don't know the command to do so. I dont need the data and that column anymore.
I tried
rails destroy migration add_image_to_users image:string
rake db:migrate
But it did not fix the problem =/
rails g migration remove_image_from_users
That will generate a new migration, and then inside the change method you can write:
remove_column :users, :image

Alter Schema in Rails 2

I need to add some columns to a table in my schema. Can someone tell me the best way to do this?
The following seems incomplete or wrong since the schema.rb file did not update to include the new column and all of the corresponding view files (edit,index,new,show) did not update to include the new column. Not to mention the bloat of all of those migration classes that get generated. Thanks
ruby script/generate migration RecordLabelToAlbums record_label:string
exists db/migrate
create db/migrate/20121130125859_record_label_to_albums.rb
Creates this:
class RecordLabelToAlbums < ActiveRecord::Migration
def self.up
end
def self.down
end
end
I then added this:
class RecordLabelToAlbums < ActiveRecord::Migration
def self.up
add_column :albums, :record_label, :text
end
def self.down
remove_column :albums, :record_label
end
end
The I ran:
rake db:migrate
Got This:
Mysql::Error: Table 'albums' already exists: CREATE TABLE albums (id int(11) DEFAULT NULL auto_increment PRIMARY KEY, created_at datetime, updated_at datetime)
The code you added is correct.
The error suggests that for some reason your system appears to think it has not yet run the original migration that created the albums table. The state of migrations (in Rails 2) is specified in a table in the database called schema_migrations -- if this gets confused then it will try to re-run migrations. I am not sure what might cause it to get confused, but I do recall this happened a couple times back in 2008 when I was using Rails 2.x.
The table is simple -- you can see what's in it from a SQL prompt -- just the names of migrations it thinks it has run, I think.
If you don't mind losing some data, you can try rake db:rollback or even rake db:reset to get back to the beginning. rake db:rollback STEP=2 will rollback the last 2 migrations.
If you need the data, correct the contents of the table by adding one or more new records referencing the migrations in app/db/migrations that may have been missed. The order is important, I think (the format changed a little in Rails 3, I don't recall how).
Any time you want to add or change the database schema, use rails to generate a migration, and then run rake db:migrate once it's ready to go.
And just asking: is there any way you can move to Rails 3. It's been out for years now, and Rails 4 is coming soon. You'll find yourself in a backwater of incompatibilities, deprecations, security and performance issues and so on if you don't take the hit and upgrade.

Rails migrations after database reset

Hi I have a general migration problem:
When I create migrations like this:
class RenameColumn < ActiveRecord::Migration
def change
rename_column :users, :hotel_stars, :rating_stars
rename_column :users, :restaurant_stars, :price_stars
end
end
and change the code in the Model-,View- and Controller file accordingly(I dont create new Model etc.):
ie.
Model: attr_accessible :rating_stars, :price_stars
(instead of :hotel_stars, :restaurant_stars )
Controller: #rating = current_user.rating_stars
When I now run the migration (rake db:migrate) -> it works!
But after a rake db:drop, rake db:create, rake db:migrate it doesn't anymore!
What is wrong with this migration? How can you create migrations that are working WITH and WITHOUT resetting the database?
Thanks!!
I think your issue is that rake db:create does not rebuild your database from schema.rb. For that you need to do rake db:setup instead of rake db:create. In any case I would try rake db:reset instead of drop/create as I believe that will accomplish what you want to do in one step.
Type rake -T for a list of available tasks and what they do.
Also see here for more information on rails migrations:
http://guides.rubyonrails.org/migrations.html
Did you ever manually alter the state of your database and/or modify a migration after it was run? If so, you messed up the state of migrations.
You "could" alleviate this by adding a migration that gets your database where your new migration expects it to be, or you could fix the migration that was altered before.
Depending on how many other developers you have, I would go for the latter in this case.

Resources