Remove Model and Table so can start again in Rails - ruby-on-rails

I created a model for comments at the start of a project, but have now come to the realisation I need to create some polymorphic relations so I can use comments with a number of other models as well. Considering the the code I already have etc, I'm thinking it might be easier for me to just start again from scratch so I can build all the views/controllers etc in the correct way for my new polymorphic world.
I see that I can run rails destroy model comments to achieve this but I have two questions on that:
Will this delete the model, migrations AND the actual DB table?
What are the implications when I want to create a new model with the exact same name?

In order to completely remove all columns &
tables that migration has created you need to run:
rails db:migrate:down VERSION=012345678 (where 012345678 should be the version number of your migration)
.............................
rails destroy model Comments
will delete your Model, pending migration, tests and fixtures
So destroy it's the opposite of generate:
$ bin/rails destroy model Oops
invoke active_record
remove db/migrate/20120528062523_create_oops.rb
remove app/models/oops.rb
invoke test_unit
remove test/models/oops_test.rb
remove test/fixtures/oops.yml
And, you can now create a new Model with the same name, as there's no trace of your previous one :)

If you have already migrated the database after creating the model:
First, rollback the changes to the database:
rake db:migrate:down VERSION=20100905201547
where version is the timestamp identifying the migration. For example, if your migration file is called 20170411182948_create_comments.rb then your version parameter should be 20170411182948
Then run
rails destroy model comments
The first command will delete the table from the actual database. The second command will delete the model and the migration file. Make sure you run them in that order as the first command is dependent on the migration file to perform the rollback (which is deleted during the second command).
If you have have not migrated the database:
The table would not have been added to your database. You can go ahead and delete your model and migration files manually or use the destroy command.

You might need to remove the table thoroughly.
Run this :
sqlite3 db/development.sqlite3
Then :
sqlite> drop table table_name;
sqlite> .quit

Related

Stucked in the model migration in Ruby on Rails

I have a problem during migrating 3 models (Game,Page,Section), which is I created 3 models and forget to save it, then directly migrate it. After that, I created a new model called User, then save it, and this User model perfectly saved and migrated successfully. After that when checked schema, those 3 models did not have any fields and did not migrated.
So I did the rake db:rollback, it only rollback to User Model, but I want those 3 Models to be rollbacked. I cannot do new migration to put new values.
Q1 : So do I need to delete those 3 models and create new models?
If it is your personal project just to learn, you can drop your database and, modify migration files and then create and migrate it.
rake db:drop
modify migration files
rake db:create
rake db:migrate
But you will lose all you data in database, so it is very bad idea for future. Better learn how you can create another migrations and add columns you need for your tables.
Look here: add_column
Ot you can always rollback few migrations using rake db:rollback STEP=n

Delete model and migration file rails 4

I was attempting to add a tagging model to my rails blog. But I accidentally generated a "Tags.rb" model as opposed to "Tag.rb", after reading the guide I realized that making "tag" plural was a mistake when it comes to model. I rolled back the migration using
rake db:rollback
and then
rails destroy model Tags.rb
and this was what i got back
invoke active_record
remove /home/migration/templates/create_table_migration.rb
remove app/models/tags.rb.rb
invoke test_unit
remove test/models/tags.rb_test.rb
remove test/fixtures/tags.rbs.yml
When I come back to the model folder though its still there.
Please help :)
Just give
rails destroy model Tag
Try using tags plural without the additional .rb, like
rails destroy model Tags
Hope this helps
You can manually delete the files, or just manually remove the "s"s.
try this
bundle exec rake db:rollback
and then delete your model as
rails destroy model <model_name>
now totaly deleted.
You can delete the migration files in migrate folder and model in your model folder and then you can again create new one which you wants.
you have to run that commands
rails g model tag
Then migrate database
rake db:migrate
First off, when generating a Rails model using rails generate model, don't add .rb to the end of the model name. Rails automatically does that so if you add .rb yourself then you end up with a model named Tag.rb.rb, which is invalid.
You're running the remove generator with "Tags.rb". Did you generate the model originally using rails generate model Tags.rb? If you did, then running rails destroy model Tags.rb will hopefully remove all the files, but since the model name is invalid, it might not work as expected (your use case is outside the intended use case of the generator). If you originally generated the model using rails generate model Tags, then running rails destroy model Tags should work.
If you originally invoked rails generate model Tags.rb, and running the remove command isn't working (which again, in understandable given that Tags.rb is an invalid name--would have been nice if the generator had originally prohibited you from generating a Tags.rb.rb file, but you can't have everything):
If you can afford to destroy your database and rerun all the migrations, the easy solution will be to manually remove the added files, destroy the database, and rerun all migrations. Then you can add the correct model using rails generate model Tag.
If you can't afford to destroy your database, then you'll need to manually find the problem migration in the migration's folder, run the down command on that migration, and then manually delete that migration file and all the other files.

How to keep overview of the migrations?

I have a question regarding my migrations in rails.
Normally when i want to add a colum to a model for i dont make extra migrations but instead i perform this steps:
rake db:rollback
next i change the migration file in db/migrations and rerune:
rake db:migrate
The biggest problem is that when i do this i loose my data.
Previous i wrote migrations from the command line with for example
rake g migration Add_Column_House_to_Users house:string
The problem with this approach is that my db/migrations folder afterwards get very large and not very clear! I mean at the end i dont know wich variables the object has! Im not an expert in rails and would like to ask you how to keep the overview over the migrations!Thanks
Just a minor thought - I just use the file db/migrate/schema.rb to determine whats in the database as opposed to tracking through the migrations
You definitely shouldn't use db:rollback with a table with existing data.
I have a few production RonR apps with a ton of data and there are 100+ entries in the migrations table and adding new migrations to tweak tables is the rails way to do things. Not sure what you mean by lucid, but your schema and data model are going to change over time and that is ok and expected.
One tip. The migrations are great, but they are just the beginning, you can include complex logic as needed to fix your existing data (like so)
Changing data in existing table:
def up
add_column :rsvps, :column_name_id, :integer
update_data
end
def update_data
rsvps = Rsvp.where("other_column is not null")
rsvps.each do |rsvp|
invite = Blah.find(rsvp.example_id)
...
rsvp.save
end
end
Another tip: backup your production database often (should do this anyway), but use it to test all of your migrations before deploying. I run scripts like this all the time for local testing:
mysql -u root -ppassword
drop database mydatabase_dev;
create database mydatabase_dev;
use mydatabase_dev;
source /var/www/bak/mydatabase_backup_2013-10-04-16.28.06.sql
exit
rake db:migrate

Ruby on Rails migration, change table to MyISAM

How does one create a Rails migration properly so that a table gets changed to MyISAM in MySQL? It is currently InnoDB. Running a raw execute statement will change the table, but it won't update db/schema.rb, so when the table is recreated in a testing environment, it goes back to InnoDB and my fulltext searches fail.
How do I go about changing/adding a migration so that the existing table gets modified to MyISAM and schema.rb gets updated so my db and respective test db get updated accordingly?
I didn't find a great way to do this. You could change your schema.rb like someone suggested and then run: rake db:schema:load, however, this will overwrite your data.
The way I did it was (assuming you are trying to convert a table called books):
Save the existing data from the CLI: CREATE TABLE tmp SELECT * FROM books;
In your new migration file, drop the books table and recreate it with :options => "ENGINE=MyISAM" like someone said in the comment
Copy the contents back: INSERT INTO books SELECT * FROM tmp
i think that if you change your schema format (config.active_record.schema_format) from :ruby to :sql, all sql will be saved there.
i'd do some tests on a fresh app first if i were you, see how it works.
You can run any sql in migrations. This worked for me:
class ChangeMapOnlyUsersEngine < ActiveRecord::Migration[5.1]
def change
MyModel.connection.execute("ALTER TABLE my_models ENGINE = 'MyISAM';")
end
end
When I did this in the other direction (InnoDB -> MyISAM) it worked fine, without loss of data so I don't think it's neccesary to create temporary tables or similar. Note that MyISAM doesn't support transactions, so any tests against the database for a corresponding ActiveRecord model will be persisted, with a risk of test pollution.

Rails remove old models with migrations

I have a bunch of rails models that I'm re-writing into a single model to simplify my code and reduce unnecessary tables.
I'm wondering what the best way to delete a model class and its table is. I want past migrations to still succeed, but I don't want to leave the empty models lying around.
Do I have to manually delete the old migrations that reference these models, then manually delete the class files?
Does anyone have any tips for the best way to do this?
All in one solution.
Run the following commands:
rails destroy model ModelName
rails g migration DropTableModelName
The former will generate a new migration file which should looks like this:
class DropTableModelName < ActiveRecord::Migration
def change
drop_table :model_name
end
end
Now run db:migrate and you're done.
If you'd like to completely get rid of of a model and its table do this:
rails destroy model Name
The question is a bit stale now, but I just did:
rails destroy scaffold <ModelName> -p
The -p flag shows "pretend" output, which is good for seeing what will happen. Remove the '-p' flag and the results will match the output. This cleaned the entire collection of M-V-C files + testing + js files + the original migration, no problem.
I guess if you are one who likes to hand edit your migrations and include multiple steps in each, losing the original migration could break db:setup, so buyer beware. Keeping one action == one migration file should avoid this potential snafu.
What about doing ruby script/destroy model? That should take care of the model and the migration.
Depending on how far into development or production you are, you may want to migrate the models out safely using a migration to remove/backup data or what not. Then as bobbywilson0 suggested, using
script/destroy model
or if you rspec anything
script/destroy rspec_model
This will remove any spec tests as well.
Or you can always just drag them to the trash folder.
You can take a look at this one at rails guide.
But I suggest, if it is possible, you should delete the models and all references to the models. This will probably save time later as you don't need to maintain the dead code in the codebase.
If you'd rather have a manual based answer:
First run the following command to identify which migrations you want removed:
rake db:migrate:status
Feel free to grep -i on it too if you're confident of your naming scheme.
Make note of all the "add x to model name" and similar alterations to your Model. These can be removed using:
rails d migration AddXToModelName
Do this for every migration besides the initial create migration. The following command will take care of the initial create migration and the files associated with the model:
rails d model ModelName

Resources