Fixing rails migration ran on server instead of git repo using Capistrano - ruby-on-rails

I upgraded Spree Commerce from version 3.0 to version 3.1 but forgot to check in the migration files on Git from my local development environment
I instead generated the migration files on the server instead; I ended up committing the migrations from my development environment to git but now I'm having all sorts of problems with deploying because it's trying to run the migration when the tables exists.
I guess I don't really need the migrations to run since it's on the server?
Running rake db:migrate:status on the server shows:
up 20151015124064 Add meta title to page.spree static content
up 20151015124065 Add render as partial for layout for spree pages.spree static content
up 20151015124066 Add pages stores.spree static content
down 20160707102753 Create spree store credits.spree
down 20160707102754 Create spree store credit categories.spree
down 20160707102755 Create spree store credit events.spree
down 20160707102756 Create spree store credit types.spree
down 20160707102757 Add missing indexes.spree
down 20160707102758 Remove duplicated indexes from multi columns.spree
down 20160707102759 Remove user index from spree state changes.spree
down 20160707102760 Add position to spree payment methods.spree
down 20160707102761 Add taxable adjustment total to line item.spree
down 20160707102762 Migrate payment methods display.spree
down 20160707102763 Spree payment method store credits.spree
down 20160707102764 Rename has and belongs to associations to model names.spree
down 20160707102765 Spree store credit types.spree
down 20160707102766 Add discontinued to products and variants.spree
down 20160707102767 Remove shipping method id from spree orders.spree
down 20160707102768 Add id column to earlier habtm tables.spree
down 20160707102769 Add indexes.spree
down 20160707102770 Add missing indices on user.spree auth
down 20160707102771 Remove show in footer from spree pages.spree static content
On my location machine it shows:
up 20151015124064 Add meta title to page.spree static content
up 20151015124065 Add render as partial for layout for spree pages.spree static content
up 20151015124066 Add pages stores.spree static content
up 20160707102753 Create spree store credits.spree
up 20160707102754 Create spree store credit categories.spree
up 20160707102755 Create spree store credit events.spree
up 20160707102756 Create spree store credit types.spree
up 20160707102757 Add missing indexes.spree
up 20160707102758 Remove duplicated indexes from multi columns.spree
up 20160707102759 Remove user index from spree state changes.spree
up 20160707102760 Add position to spree payment methods.spree
up 20160707102761 Add taxable adjustment total to line item.spree
up 20160707102762 Migrate payment methods display.spree
up 20160707102763 Spree payment method store credits.spree
up 20160707102764 Rename has and belongs to associations to model names.spree
up 20160707102765 Spree store credit types.spree
up 20160707102766 Add discontinued to products and variants.spree
up 20160707102767 Remove shipping method id from spree orders.spree
up 20160707102768 Add id column to earlier habtm tables.spree
up 20160707102769 Add indexes.spree
up 20160707102770 Add missing indices on user.spree auth
up 20160707102771 Remove show in footer from spree pages.spree static content
I presume the migration status on the server should be up not down.
Is there any tips how I should approach this?

If you don't have any data to lose you can drop those tables from your sql console and re-run capistrano deployment or you can manually up the migration file from the server by
rake db:migrate:up VERSION=20151015124064
where version is second column of the result of rake db:migrate:status
Note: remember you have to drop those tables on both cases

If you do not want to lose data and do it all over again there is an another approach that you can try.
A migration is marked as up or down based on whether migration version exists as a record within the schema_migrations table.
So, one way you can fix your issue is to add a file app/models/schema_migration.rb containing the following:
class SchemaMigration < ActiveRecord::Base
self.primary_key = :version
attr_accessible :version
# you can call the method below via console or even call
# or execute the commands directly from the rails console
def self.fix_migrations
# basically a list of all migrations that you run on server but are not marked as up
down_migrations = %w(20160707102753 20160707102754 ... 20160707102771)
down_migrations.each do |m|
# this will add an entry in the schema_migrations datatable
# on server so rake db:migrate won't try to run these again
SchemaMigration.create(version: m)
end
end
end
And then via rails console, you execute: SchemaMigration.fix_migrations.
In case you need to run a specific migration again or if you accidentally added a migration version that has never been executed before, you can always remove the entry from schema_migrations using SchemaMigration.find_by_version('xxxx').delete. This will allow rake db:migrate to try to run that migration again.

Related

Deleted Migration Files and Heroku

I asked about this once already, but I didn't get a working response, and I may have a better way of asking this question.
Long story short, I've deleted some problematic migration files, (the problem is coming from out-of-order migration files; there is an add_column_to_stocks before a create_stocks file), but for whatever reason, heroku continues to want to migrate these old, deleted files. I have no idea where these files are being stored.
If I do a heroku db:migrate:status, this is the response:
Status Migration ID Migration Name
--------------------------------------------------
up 20171231042756 Create articles
up 20171231044214 Add description to articles
up 20180116183526 Create users
up 20180116191414 Add user to articles
up 20180116195212 Add password digest to users
up 20180305082108 Create categories
up 20180305090315 Create article categories
down 20180515064500 Add latest price to stocks
down 20180517202216 Add timetables to stock
down 20180517205823 Add updatedtime to stocks
down 20180521021514 Create user stocks
The problems start at the first down file.
My local migration folder looks more like this:
20171231042756 Create articles
20171231044214 Add description to articles
20180116183526 Create users
20180116191414 Add user to articles
20180116195212 Add password digest to users
20180305082108 Create categories
20180305090315 Create article categories
20180515064499 Create stocks.rb
20180521021514 Create user stocks.rb
No matter what changes I make to my local migration files, it continues to want to migrate these problematic files, so I always get back the response:
PG::UndefinedTable: ERROR: relation "stocks" does not exist
: ALTER TABLE "stocks" ADD "latest_price" decimal
I tried getting into the heroku psql console and deleting them manually, but a delete from schema_migrations where version = 20180515064500 brings back a DELETE 0 response, meaning it hasn't deleted anything.
I'm friggen stumped and I've spent about a week and a half beating my head in over this.
Thank you all in advance!! Any help is appreciated.
File with migration number 20180515064500 should be gone as it is attempting to modify the table which doens't exist.
Remove the files which are breaking the migrations:
git rm db/migrate/20180515064500*.rb
and deploy on heroku.
Look if in your db files, your version of rails is indicated there (5.2 for example):
In your files that are in down mode.
class CurrencyCreateUsers <ActiveRecord :: Migration [5.2]
then rake db: migrate

manually adding an integer field to rails scaffold

I'm new to rails...I made a scaffold "Reviews" but want to add another field "ratings", as an integer. I did the following:
added t.integer :ratings in the migration file..ran rake db:migrate
in spec folder: added it in views/app/ edit, index, new, show
in app/views/app added it in the json files
in app/controllers/app added it in the review_params function
still however whenever I try to reference (by showing a Review) it I get
undefined method `ratings' for #
There must be something else I need to add somewhere to have it be part of my Reviews scaffold. I've been trying to figure it out for 5 hours but still have not. When I try to remake a scaffold and run rake db:migrate I get an error saying that the databases already exist so I would like to just manually add it to my existing one if possible, I just can't seem to figure out how even though I've already done it once for a string.
Any help is appreciated thank you.
To add an integer field to a model you can do something like this.
rails generate migration AddRatingToReviews rating:integer
This should handle everything for you by generating a new migration file like so.
class AddRatingsToReviews < ActiveRecord::Migration
def change
add_column :reviews, :rating
end
end
Then you can run rake db:migrate to add the column to your review model.
NOTE: Before doing all of this, please delete all your manual changes. If necessary use rake db:rollback which will rollback your most recent rake db:migrate.
Recommendation
If you are new to rails and don't understand MVC, I suggest not using scaffolding because you'll have a tough time knowing what it is doing. Go through this awesome tutorial by Michael Hartl to really learn rails quickly. http://ruby.railstutorial.org/
*Awesome gem *
Use the annotate gem to display the attributes contained within your model directly in your name_of_model.rb files.
https://github.com/ctran/annotate_models
rails generate migration AddRatingsToReviews ratings:integer
Then
rake db:migrate
If you have not done any major changes in your generated scaffold.
Simplest way to get the ratings across views would be as below:
Rollback the changes that you have migrated
rake db:rollback VERSION=version_number
Where replace version_number with the version_number prefixed on your migration file.
For eg: If your migration filename is 20140314190622_create_reviews.rb then command should be
rake db:rollback VERSION=20140314190622
Destroy the scaffold of Review
rails d scaffold Review
After this generate the scaffold again with the integer field
rails g scaffold Review ratings:integer .... ## Add other field in place of ....

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.

Rails/Mongoid database migrations

I am currently working on a rails app where we are using mongoid/mongoDB on the back-end. I understand that I don't need ActiveRecord like migration to migrate the schema, but I do need to migrate data as I change mongoid model definitions. Is anyone else out there running into the same scenario, if so how are you handling it?
Even though you're not making schema changes, you may need to move data between fields, or remove fields that are no longer used in the codebase. It's nice to have migrations that you can run when you deploy new code. I recommend using a gem called mongoid_rails_migrations. This provides you with migration generators like you're used to and provides some organization to migrating data.
class MyMigration < Mongoid::Migration
def self.up
MyModel.all.each do |model|
# label was renamed to name
model.set :name, model[:label] # copy the data from the old field to the new one
model.remove_attribute :label # remove the old field from the document
model.save!
end
end
end
Write a custom rake task to migrate the data as needed
This question addresses the same issue of creating custom migrations in a mongoid setup.
Runtime changing model with mongodb/mongoid
I had the some scenario recently, where I have to do some data migration only once (basically update dirty data);
So what I did have a mongoid migrations in /db/migrate/ and override the db:migrate task so that it creates a collection in mongo db of that app itself, say "migrations", that record the migration that got fired, with that, none of the migration will run again, and you can keep adding migrations with some hierarchy (if in case migration is interdependent).

Having trouble getting started with Ruby on Rails

I'm wondering if someone can address some of the issues I am having? I create a rails app:
rails myapp -d mysql
cd myapp
haml --rails .
rake db:create:all
Then I want to use a mysql client to create tables. Lets say users and customers. A customer is also a user so you have schema like this:
users
----------------
id int, not null, primary key, auto increment
first_name varchar(50) not null
last_name varchar(50) not null
email varchar(50) not null unique
password varchar(50) not null
created_at datetime not null
updated_at datetime not null
customers
----------------
id int, not null, primary key, auto increment
user_id int, unique
-- some other stuff that is customer specific
what rails script commands do I need to run to get model, views and controllers created and completely filled out under my rails app? I tried this:
ruby script/generate scaffold user
ruby script/generate scaffold customer
which creates the files but the models are empty:
class User < ActiveRecord::Base
end
whats the deal? Also, I want to create an administration section to manage stuff. I figured out that I need to add routes for those:
map.namespace :admin do |admin|
admin.resources :users
admin.resources :customers
end
what else do I need to get the administration section going?
Also here are the versions of ruby/gems I am running:
ruby 1.8.6
rails 2.3.5 & 2.3.2 <- I'm using 2.3.2 because haml
wasn't working (or some other plugin) with 2.3.5
haml 2.2.15
rspec 1.2.9 <- I saw from another thread that I might need
this when creating an adminstration section (rspec_controller etc)
Models are supposed to be empty by default because database schema is saved into the schema.rb file and managed using migrations.
From your answer I understand you are looking for a prepackage solution to write a couple of configurations and get everything, from controller to administration cooked for you.
I'm sorry, Rails doesn't offer you this feature. If you want an administration section you actually have to code it.
It includes:
creating your views and templates
creating your actions
mapping your routes
writing your tests
The scaffold only provides you a starting point but this is a starting point you should adapt and extend to your needs.
If you want the scaffold to auto-generate your initial views according to your database table, you can pass the arguments to the command line tool
ruby script/generate scaffold user name:string age:integer
But if you want to add a new field later, you'll have to write a new migration and edit your views/actions accordingly.
More information are available in the Rails Guides and Wiki.
Rails is designed for database independence with all the 'creation' done via the migrations located in db/migrate.
To create the appropriate DB tables you then simply run rake db:migrate and any migrations will be executed to create the necessary DB tables.
A good place for more information is the Rails Guides which has an example application to work through.

Resources