I've generated a scaffold and then migrated my database. After that, I destroyed my scaffolding and then generated scaffold again and try to migrate my database but I got an error that this table already exists. How can I delete that table from the database?
One other easy way to do so :
open rails console and use this command :
ActiveRecord::Migration.drop_table(:your_table_name)
If you haven't pushed your code then the solution given by #Cryptex Technologies works fine. But if you have(i.e if you are using version control) then i won't recommend that approach. In that case you should create a new migration something like this:
class RemoveTable < ActiveRecord::Migration[5.2]
def up
drop_table :table_name
end
def down
create_table :table_name do |t|
t.string :field_name_1
t.text :field_name_2
t.timestamps
end
add_index :table_name, :field_name_1, unique: true
end
end
To delete that table, you need to run the command
rake db:rollback
and if you want to delete the database of your current application.
then you need to run the command
rake db:drop.
Rails automatically generates migration, thanks to the command line generator.
For instance, if you want to remove the Users Table write a command line statement like this:
rails generate migration DropUsersTable
This will generate the empty .rb file in /db/migrate/ that still needs to be filled to drop the “Users” table in this case.
A Quick-and-Dirty™ implementation would look like this:
class DropUsersTable < ActiveRecord::Migration
def up
drop_table :users
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
It’s “correct” as it shows that the migration is one-way only and should not/can not be reversed. But in order to make a truly clean job in case these modifications were to be reversed we need to have a symmetrical migration (assuming we could recover the lost data), which we can do by declaring all the fields of our table in the migration file:
class Dropusers < ActiveRecord::Migration
def change
drop_table :users do |t|
t.string :name, null: false
t.timestamps null: false
end
end
end
This can be long if the model is complex, but it ensures full reversibility.
Here again, changes will enter effect as usual after running rake db:migrate.
I'm totally stuck here! I want to add a unique index so that no two records in an association table can have the same combination of user_id and course_id.
I have created the following migration file in rails:
class CreateSignups < ActiveRecord::Migration
def change
create_table :signups do |t|
t.integer :course_id
t.integer :user_id
t.timestamps null: false
end
add_index :signups, :course_id
add_index :signups, :user_id
add_index :signups, [:course_id, :user_id], unique: true
end
end
...but for some reason, the unique 'course_id & user_id' is not being represented in the schema.rb and using the rails console the system lets me manually create a multiple records where the course_id and the user_id are exactly the same.
The signups table is managed by the Signup model and has an integer primary key called 'id'. The course and user Model & database table follow standard rails naming convention.
Can anyone see why it's the unique criteria is not being understood in this migration?
Thanks in advance!
Did you already run your migration once (to create table) and then add the index? You can check it by doing following:
bundle exec rails dbconsole
select * from schema_migrations;
If your migration version is already recorded in the schema_migrations table, and doing rake db:migrate won't run it again.
To add indexes, you have 2 options:
Rollback the migration for CreateSignups. This will drop the current table and then doing rake db:migrate will re-create the table with indexes.
If you don't want to loose the data in previous step, then you'll have to explicitly create indexes in MySQL from rails dbconsole.
So I accidentaly made a model in Ruby on Rails on which I wrote an attribute twice, with the same name and type. If I check my migration it looks like this:
class CreateTable < ActiveRecord::Migration
def change
create_table :table do |t|
t.text :Total
t.text :Total
t.timestamps
end
end
end
The name is not really Table, but you get the idea.
My question is how will this be reflected on the db, since running the migrations caused no problem. I don't think it's posible to have to columns with the same id, so I'm guessing it was only created once.
It will create the column just once. Your table is valid. But i advise you to rollback the migration, delete the migration file and create a new migration with valid column names(Given no one else has pulled this change of yours).
I have created a database with devise and the nifty generator. I'm trying to make a new database with the nifty generator (rails g nifty:scaffold Asset user_id:integer), but when I try to migrate the database (rake db:migrate), I get the following error:
charlotte-dator:showwwdown holgersindbaek$ rake db:migrate
== DeviseCreateUsers: migrating ==============================================
-- create_table(:users)
rake aborted!
An error has occurred, all later migrations canceled:
Mysql2::Error: Table 'users' already exists: CREATE TABLE `users` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `email` varchar(255) DEFAULT '' NOT NULL, `encrypted_password` varchar(128) DEFAULT '' NOT NULL, `reset_password_token` varchar(255), `reset_password_sent_at` datetime, `remember_created_at` datetime, `sign_in_count` int(11) DEFAULT 0, `current_sign_in_at` datetime, `last_sign_in_at` datetime, `current_sign_in_ip` varchar(255), `last_sign_in_ip` varchar(255), `name` varchar(255), `created_at` datetime, `updated_at` datetime) ENGINE=InnoDB
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
I'm following a tutorial and have quite a hard time understanding why this happens. Can anyone explain what is going on?
In your create_users migration (APP_ROOT/db/migrate/..), add drop_table :users right before create_table :users and run rake db:migrate. It will remove the users table before recreating it. You can remove that line of code after running this migration so it doesn't give you errors later on. Just a small fix if you dont have UI access to a database (on heroku, for example).
You need to drop that table from the sql lite console (You will lost all the data contained in it)
Access the sql lite console, type in terminal
mysql <DB NAME HERE>
Drop table (dont forget the last ; (semicolon))
drop table table_name;
run db:migrate again
bin/rake db:migrate
Hope it helps, it worked for me
If you wanna play safe and don't want to lose any data then you can check if the table exists in your database.
class DeviseCreateUsers < ActiveRecord::Migration
def up
if table_exists?(:users)
# update or modify columns of users table here accordingly.
else
# create table and dump the schema here
end
end
def down
# same approach goes here but in the reverse logic
end
end
The migration is trying to create a table that already exists in your database.
Try to remove the user table from your database. Something went wrong with you migration process. You should also compare your schema.rb version with your db/migrate/*.rb files.
Clarification:
It seems that many SO users don't agree with my reply, either because they consider it inaccurate or not recommended.
Removing a table is always destructive, and I think that everyone understands that.
I should have mentioned add_column, since the table was being created in another migration file.
If you know the database was created properly, you can just comment out the creation part of the migration code. For example:
Class ActsAsVotableMigration < ActiveRecord::Migration
def self.up
# create_table :votes do |t|
#
# t.references :votable, :polymorphic => true
# t.references :voter, :polymorphic => true
#
# t.boolean :vote_flag
#
# t.timestamps
# end
#
# add_index :votes, [:votable_id, :votable_type]
# add_index :votes, [:voter_id, :voter_type]
end
def self.down
drop_table :votes
end
end
If the table was created, but later commands weren't completed for some reason, you can just leave the later options for example:
Class ActsAsVotableMigration < ActiveRecord::Migration
def self.up
# create_table :votes do |t|
#
# t.references :votable, :polymorphic => true
# t.references :voter, :polymorphic => true
#
# t.boolean :vote_flag
#
# t.timestamps
# end
add_index :votes, [:votable_id, :votable_type]
add_index :votes, [:voter_id, :voter_type]
end
def self.down
drop_table :votes
end
end
If you don't have any significant data in your database to preserve however you can just have it drop the table and all the data and create it fresh. For example (notice the "drop_table :votes", in the self.up):
class ActsAsVotableMigration < ActiveRecord::Migration
def self.up
drop_table :votes
create_table :votes do |t|
t.references :votable, :polymorphic => true
t.references :voter, :polymorphic => true
t.boolean :vote_flag
t.timestamps
end
add_index :votes, [:votable_id, :votable_type]
add_index :votes, [:voter_id, :voter_type]
end
def self.down
drop_table :votes
end
end
Don't delete tables. Data > migrations!
The version of the database already reflects the changes the error-causing migration is trying to add. In other words, if the migration could be skipped, then everything would be fine. Check the db_schema_migrations table and try inserting the version of the erroneous migration (e.x, 20151004034808). In my case this caused subsequent migrations to execute perfectly and everything seems fine.
Still not sure what caused this problem.
If your app is new and you don't care about the data in your database, simply:
rake db:reset
I think this is an issue unique or more common to mysql in rails, possible having to do with the mysql2 gem itself.
I know this because I just switched from sqlite to mysql and just started having this problem systematically.
In my case, I simply commented out the code that had already run and ran the migration again (which I'm not adding more detail to because it looks like the guy above me did that).
I had a similar problem when trying to add Devise authentication to an existing Users table.
My solution: I found that I had two migrate files, both trying to create the Users table. So rather than deleting the table (probably not the best habit to form), I commented out the first (original) migrate file that created the Users table and then left the Devise migrate file as-is. Re-ran the migration and it worked fine.
As it turns out, the Devise file wasn't causing the problem; I can see that it is "changing" the table, not "creating it", which means that even without the devise installation, a db:migrate probably would have caused the same issue (though I haven't tested this).
If you want to keep your data, rename the table, but do it in the migration to save time, then remove it once the migration has ran.
Place at the top part of the up section of the migration file.
rename_table :users, :users2
First
ruby script/generate model Buyer id:integer name:string
after generating Buyer model, I did
rake db:migrate
it was working fine.
After 1 day I have executed below command
ruby script/generate model Seller id:integer seller_name:string
after generating Seller model, I did
rake db:migrate
I got an error, that Buyer table is already exists. why? we have different timestamp file.
class CreateBuyer < ActiveRecord::Migration
def self.up
create_table :buyer do |t|
t.string :name
t.text :description
t.decimal :price
t.integer :seller_id
t.string :email
t.string :img_url
t.timestamps
end
end
def self.down
drop_table :ads
end
end
and another one is
class CreateSellers < ActiveRecord::Migration
def self.up
create_table :sellers do |t|
t.integer :nos
t.decimal :tsv
t.decimal :avg_price
t.timestamps
end
end
def self.down
drop_table :sellers
end
end
I used Rails 2.3.11 and rake 0.8.7
Are you sure there were no errors generated when you ran the first migration? If an error is encountered while running a migration, the parts that were already run will still be in the database, but schema_migrations won't be updated with the migration timestamp. Therefore, the next time you try to run migrations, it'll try to re-run the first part of the failed migration, which will generate errors since it's already been run.
Updated: If you look in the error output you added (by the way, please add to the question rather than a comment, so it's formatted and the whole thing is included) you can see that the first Execute db:migrate is running the migration CreateBuyer. This confirms that your migration did not complete the first time you ran it or has since been unsuccessfully rolled back. To fix this, manually drop the buyer table, then rerun your migrations.
As a note, there's at least a couple issues in your CreateBuyers migration:
The table name should be buyers (plural) rather than buyer (singular)
The down part of the migration is dropping the table ads instead of buyers
The second problem there could explain why you're having trouble running migrations now, actually. If you rolled back the CreateBuyers migration, it would have dropped your ads table and left buyers in place.