DB:Migrate for Ruby On Rails - ruby-on-rails

I am working in Ruby on Rails.
I am updating a database with users locally:
Using the "rails console"
Running rails server
Checking on localhost:3000
The users are added on my local host.
I then try and run steps 3-7
Make changes to local code
Run any migrations LOCALLY
Add all changed files to Git git add .
Commit all added files to git git commit -m "Adding features"
Push the changes to Heroku git push heroku master - assuming you are using heroku as your remote name and you are working in the master branch
If you have migrations run heroku run rake db:migrate to run the migrations ON HEROKU
Following migrations do heroku restart
After step 6 I get this as a result:
"Running `rake db:migrate` attached to terminal... up, run.5819
Migrating to CreateUsers (20140812155921)
== 20140812155921 CreateUsers: migrating ======================================
-- create_table(:users)
-> 0.0572s
== 20140812155921 CreateUsers: migrated (0.0574s) =============================
Migrating to AddIndexToUsersEmail (20140812200300)
== 20140812200300 AddIndexToUsersEmail: migrating =============================
-- add_index(:users, :email, {:unique=>true})
-> 0.0252s
== 20140812200300 AddIndexToUsersEmail: migrated (0.0254s) ====================
Migrating to AddPasswordDigestToUsers (20140812204144)
== 20140812204144 AddPasswordDigestToUsers: migrating =========================
-- add_column(:users, :password_digest, :string)
-> 0.0039s
== 20140812204144 AddPasswordDigestToUsers: migrated (0.0041s) ================
Migrating to AddRememberTokenToUsers (20140814171549)
== 20140814171549 AddRememberTokenToUsers: migrating ==========================
-- add_column(:users, :remember_token, :string)
-> 0.0067s
-- add_index(:users, :remember_token)
-> 0.0171s
== 20140814171549 AddRememberTokenToUsers: migrated (0.0275s) =================
Migrating to AddAdminToUsers (20140815204326)
== 20140815204326 AddAdminToUsers: migrating ==================================
-- add_column(:users, :admin, :boolean, {:default=>false})
-> 0.0963s
== 20140815204326 AddAdminToUsers: migrated (0.0977s) =========================
Migrating to CreateMicroposts (20140815212754)
== 20140815212754 CreateMicroposts: migrating =================================
-- create_table(:microposts)
-> 0.0256s
-- add_index(:microposts, [:user_id, :created_at])
-> 0.0350s
== 20140815212754 CreateMicroposts: migrated (0.0611s) ========================
Migrating to CreateRelationships (20140816000750)
== 20140816000750 CreateRelationships: migrating ==============================
-- create_table(:relationships)
-> 0.0217s
-- add_index(:relationships, :follower_id)
-> 0.0385s
-- add_index(:relationships, :followed_id)
-> 0.0195s
-- add_index(:relationships, [:follower_id, :followed_id], {:unique=>true})
-> 0.0226s
== 20140816000750 CreateRelationships: migrated (0.1057s) ====================="
When I do:
heroku open
and try to log in it now says my user information is invalid and heroku support says there are no user records.
Does anyone know what I can do here? This folder was also copied over from another project I was working on, so I deleted the .git file and created a new repository. I just don't know why my database will work locally but not on heroku.
Thanks much.
Best,
David

The users you are creating are stored in your local database only. When you push to Heroku you need to create the users in the Heroku database, either through your user registration interface or through a seeds file.

Here's a sample seed file that you might want to push
# /db/seeds.rb
User.where(email: 'admin#domain.com').first_or_create! do |user|
user.name = 'admin'
user.password = 'temporarypassword'
end
Then push this to the server and run the seeds, you'll need to login and change the password as soon as possible, since the password is pushed into the version control.

Related

Rails test DB constantly losing my PostgreSQL functions

My project uses a few custom PostgreSQL stored functions for some features that would be a pain in raw SQL or ActiveRecord. Every now and then I will run the RSpec test suite, and find that all my stored functions have been blown away. Re-running the migrations to create them fixes the problem, but "rake db:structure:load" does NOT.
I am deeply confused. I never drop either the dev or test database unless this happens, but my functions are like Schrodinger's PL/pgSQL. I am REALLY hoping this never happens in production.
Here is an example of a failing test and my attempts to fix it:
ActiveRecord::StatementInvalid:
PG::UndefinedFunction: ERROR: function round_half_down(numeric) does not exist
# Damn. We have to drop the database so we can reload structure.sql:
$ RAILS_ENV=test rake db:drop
$ RAILS_ENV=test rake db:create
# load structure.sql instead of schema.rb:
$ RAILS_ENV=test rake db:structure:load
# Not fixed:
ActiveRecord::StatementInvalid:
PG::UndefinedFunction: ERROR: function round_half_down(numeric) does not exist
$ RAILS_ENV=test rake db:migrate:redo VERSION=20160421184708
== 20171002190107 CreateRoundHalfDownFunction: reverting ======================
-- execute("DROP FUNCTION IF EXISTS round_half_down(numeric)")
-> 0.0004s
== 20171002190107 CreateRoundHalfDownFunction: reverted (0.0005s) =============
== 20171002190107 CreateRoundHalfDownFunction: migrating ======================
-- execute("CREATE OR REPLACE FUNCTION ROUND_HALF_DOWN(NUMERIC)\n RETURNS NUMERIC LANGUAGE SQL AS\n$FUNC$\n SELECT CASE WHEN ($1%1) < 0.6 THEN FLOOR($1) ELSE CEIL($1) END;\n$FUNC$\n")
-> 0.0014s
== 20171002190107 CreateRoundHalfDownFunction: migrated (0.0014s) =============
Now it is fixed!
Yes, I verified that the function is present in structure.sql:
--
-- Name: round_half_down(numeric); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION round_half_down(numeric) RETURNS numeric
LANGUAGE sql
AS $_$
SELECT CASE WHEN ($1%1) < 0.6 THEN FLOOR($1) ELSE CEIL($1) END;
$_$;
For the record, this stopped happening to me with newer versions of the pg gem and PostgreSQL itself. I also added config.active_record.schema_format = :sql to application.rb, because my application makes heavy use of Postgres-specific features, and a number of stored functions.

rails - list of tenants to migrate appears to be empty when loading a schema

what does it mean if in rails I run db:schema:load, and the schema loads until it says that "the list of tenants to migrate appears to be empty"?
And what ways are available to solve this?
As in here (sorry I am unable to format it better):
...
--create_table("users", {:force=>:cascade})
-> 0.4490s
-- create_table("web_migrations", {:id=>false, :force=>:cascade})
-> 0.6138s
-- initialize_schema_migrations_table()
-> 0.0332s
[WARNING] - The list of tenants to migrate appears to be empty. This could mean a few things:
1. You may not have created any, in which case you can ignore this message
2. You've run `apartment:migrate` directly without loading the Rails environment
* `apartment:migrate` is now deprecated. Tenants will automatically be migrated with `db:migrate`
Note that your tenants currently haven't been migrated. You'll need to run `db:migrate` to rectify this.
I noticed that maybe db:schema:load runs twice?
It starts fine:
-- create_table("asset_status", {:force=>:cascade})
-> 0.5029s
-- create_table("asset_type", {:force=>:cascade})
-> 0.2904s
[continues...]
-- create_table("web_migrations", {:id=>false, :force=>:cascade})
-> 0.3347s
-- initialize_schema_migrations_table() -> 1.1729s
and after this again:
-- create_table("asset_status", {:force=>:cascade})
-> 0.6400s
-- create_table("asset_type", {:force=>:cascade})
-> 0.5805s
[continues...]
is it wrong?
In case it helps someone in future, You can use single tenant migration in-case there is no other solution.
Run DB=tenant_name rake db:migrate
This will migrate the database for a specific tenant.

heroku run rake db:migrate reverts migrations

I am running my app on heroku, using the heroku pg stack, and when I run db:migrate it reverts my previous migrations instead of moving forward.
rake db:version shows the current migration
Current version: 20160516172744
rake db:migrate:status shows all migrations as up
......(more above all up)
up 20160512175053 Create spree roles permissions.spree admin roles and access
up 20160512175054 Add editable is default and index on editable is default and name to spree roles.spree admin roles and access
up 20160513135317 Add indexes for speed
up 20160513140704 Add filter search params to spree product
up 20160516172744 Add tsvector colums to spree products
But when I hit heroku run rake db:migrate this is the output:
Migrating to AddTsvectorColumsToSpreeProducts (20160516172744)
== 20160516172744 AddTsvectorColumsToSpreeProducts: reverting =================
-- execute(" DROP FUNCTION IF EXISTS spree_products_tsv_trigger() CASCADE;\n")
-> 0.0031s
-- remove_index(:spree_products, :tsv)
-> 0.0058s
-- remove_column(:spree_products, :tsv)
-> 0.0025s
== 20160516172744 AddTsvectorColumsToSpreeProducts: reverted (0.0122s) ========
Migrating to AddFilterSearchParamsToSpreeProduct (20160513140704)
== 20160513140704 AddFilterSearchParamsToSpreeProduct: reverting ==============
-- remove_column(:spree_products, :designer_id)
-> 0.0062s
-- remove_column(:spree_products, :main_taxon_id)
-> 0.0024s
-- remove_column(:spree_products, :colour_id)
-> 0.0025s
-- remove_column(:spree_products, :size_id)
-> 0.0045s
-- remove_column(:spree_products, :condition_id)
-> 0.0023s
-- remove_column(:spree_products, :on_site)
-> 0.0023s
-- remove_column(:spree_products, :sgd_price)
-> 0.0025s
-- remove_column(:spree_products, :search_designer)
-> 0.0022s
-- remove_column(:spree_products, :search_category)
-> 0.0021s
-- remove_column(:spree_products, :search_sku)
-> 0.0022s
== 20160513140704 AddFilterSearchParamsToSpreeProduct: reverted (0.0341s) =====
.....(cont.)
Any ideas?
-Dan
rake db:migrate will, without any arguments, only migrate up to the latest version. If you ever see it migrate down, you most likely have the VERSION environment variable set to some value (see the docs for explanation of how that variable works), and Rails is trying to migrate to that version.
In your case, per the comments, it looks like you'd set VERSION=v3 in your environment. Rails is likely casting v3 to 0 and trying to migrate all migrations down.

Using rake db:migrate inside another task leaves pending migrations

I'm new to rake and I'm trying to find my way in automating some tasks. So I wrote my first rake task and failed:
namespace :app do
desc "Leaves application like new"
task :reset => :environment do
Rake::Task['db:drop:all'].invoke
Rake::Task['db:create:all'].invoke
Rake::Task['db:migrate'].invoke
Rake::Task['db:seed'].invoke
end
end
I'd like to know why this isn't working. After calling:
rake app:reset
everything runs fine, I can see the migration messages on screen, like this:
== CreateGalerias: migrating =================================================
-- create_table(:galerias)
NOTICE: CREATE TABLE will create implicit sequence "galerias_id_seq" for serial column "galerias.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "galerias_pkey" for table "galerias"
-> 0.1191s
== CreateGalerias: migrated (0.1194s) ========================================
But, at the end I get this message:
You have 11 pending migrations:
20110704052637 CreatePersonas
20110709100632 CreateOrganizaciones
20110709100646 CreateEventos
20110816102451 CreateMembresias
20110816155851 CreateCelebraciones
20110822135820 ActsAsTaggableOnMigration
20120410063100 CreateDocumentos
20120507200516 CreateUsuarios
20120515214226 ActivaUnnaccent
20120516091228 CreateGalerias
20120517004708 SetupHstore
Run `rake db:migrate` to update your database then try again.
Didn't it just migrated the database? why is it complaining about it?
Keep in mind that db:drop:all and db:create:all operate on all environments, and db:migrate and db:seed do not, so you are probably migrating in an unintended environment. Try changing db:drop:all to db:drop and db:create:all to db:create, and run the task specifying a particular environment like:
rake RAILS_ENV=production app:reset

facing a postgres error while running rake migration

I am getting the following uuid error while running a rails app with postgres as backend. Can someone help me out with which dependency is needed.
[root#localhost webapp]# rake db:migrate
(in /root/mysite/webapp)
== CreateContributors: migrating =============================================
-- create_table(:contributors, {:id=>false})
-> 0.0121s
-- execute("alter table contributors add primary key (id)")
NOTICE: ALTER TABLE / ADD PRIMARY KEY will create implicit index "contributors_pkey" for table "contributors"
-> 0.0797s
-- execute("alter table contributors alter column id set default uuid_generate_v1()::varchar")
rake aborted!
An error has occurred, this and all later migrations canceled:
PGError: ERROR: function uuid_generate_v1() does not exist
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
: alter table contributors alter column id set default uuid_generate_v1()::varchar
The uuid_generate_v1() function is part of the uuid-ossp package and you have to install that into PostgreSQL before you can use it. You should have a file called uuid-ossp.sql in your PostgreSQL contrib directory. You can install the package with:
$ psql -d your_database < /the/path/to/uuid-ossp.sql
You'll probably want to run that as the database super user.

Resources