Rails Heroku change column data type - ruby-on-rails

I run this command for deploying database to heroku
heroku run rails db:migrate
But I got this error
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedObject: ERROR: type "dateti" does not exist
LINE 1: ALTER TABLE "users" ADD "activated_at" dateti
^
After that I changed wrong datatype "dateti" to "datetime"
class AddActivationToUsers < ActiveRecord::Migration[7.0]
def change
add_column :users, :activation_digest, :string
add_column :users, :activated, :boolean, default: false
add_column :users, :activated_at, :datetime
end
end
But nothing changed. Still get this error. For development and test I use sqlite3 and for production postgresql. This error appear only when I try to deploy to heroku. On local database everything works.
database.yml file
# SQLite. Versions 3.8.0 and up are supported.
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
# gem "sqlite3"
#
default: &default
adapter: sqlite3
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
development:
<<: *default
database: db/development.sqlite3
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *default
database: db/test.sqlite3
production:
adapter: postgresql
encoding: unicode
# For details on connection pooling, see Rails configuration guide
# https://guides.rubyonrails.org/configuring.html#database-pooling
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
database: sample_app_production
username: sample_app
password: <%= ENV['SAMPLE_APP_DATABASE_PASSWORD'] %>

Before change activited_at (datetime) in AddActivationToUsers file. You must rollback AddActivationToUsers in db.
rails db:rollback STEP=n (n migrations where n is the number of recent migrations you want to rollback)
You change activited_at :datetime and save
rails db:migration

Related

Activerecord Migrations multiple postgresql database

I have multiple databases. All the migrations for the main database human_development runs fine. The second database is called animals and the migrations fail.
database.yml:
default: &default
adapter: postgresql
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
timeout: 5000
encoding: unicode
user: blah
development:
<<: *default
database: human_development
animals:
<<: *default
database: animals
Migrations that are failing:
class SomeTable < ActiveRecord::Migration[5.2]
def change
ActiveRecord::Base.establish_connection("animals")
create_table :some_table, id: :uuid do |t|
t.string :type
t.timestamps
end
ActiveRecord::Base.establish_connection(Rails.env)
end
end
I have also tried the following, non worked:
def connection
ActiveRecord::Base.establish_connection("animals").connect
#ActiveRecord::Base.establish_connection("animals".to_sym).connect
end
establish connection out side of the change
ActiveRecord::Base.establish_connection("animals").connect
# also tried with to_sym
If I run "rails db:migrate", passing the database name as a string I get the following error:
rake aborted!
ActiveRecord::AdapterNotSpecified: database configuration does not specify adapter
.../db/migrate/2019_some_tables.rb:2:in
and if I run the rails db:migrate with to_sym I get the following error:
-- create_table(:some_table, {:id=>:uuid})
rake aborted!
ActiveRecord::StatementInvalid: PG::ConnectionBad: connection is closed: SELECT pg_advisory_unlock
Caused by:
PG::ConnectionBad: connection is closed
Caused by:
StandardError: An error has occurred, this and all later migrations canceled:
PG::ConnectionBad: connection is closed: ROLLBACK
Caused by:
ActiveRecord::StatementInvalid: PG::ConnectionBad: connection is closed: ROLLBACK
Caused by:
PG::ConnectionBad: connection is closed
The migration file should be the same for all databases
class SomeTable < ActiveRecord::Migration[5.2]
def change
create_table :some_table, id: :uuid do |t|
t.string :type
t.timestamps
end
end
end
then in your console you run
# for the main db
rails db:migrate
# for the animals db
RAILS_ENV=animals rails db:migrate
#Eyeslandic Thank you so much, that helped a lot!
In case anyone else runs into the same problems. Looks like rails 6 is going to have a better solution for this, but meanwhile, here are additional changes I had to make:
database.yml: I wanted to keep the migrations in a separate folder:
├── db
│   ├── migrate
│   ├── schema.rb
│   └── seeds.rb
├── animals_db
│   └── migrate
animals:
<<: *default
database: animals
migrations_paths: animals_db/migrate
Create a new environment: config/environments/animals.rb
Change config/secrets.yml to include new environment
Generate secret: RAILS_ENV=animals rake secret
Save the secret in .env file or export it
Create the database: rails db:create RAILS_ENV=animals
Create the migration in animals_db but here is the catch. I had to include the following in def change
def change
create_table :some_table, id: :uuid do |t|
enable_extension "uuid-ossp"
enable_extension "pgcrypto"
t.string :type
t.timestamps
end
end
Run the migration: rails db:migrate RAILS_ENV=animals
You may need to change config/cable.yml as well to include new environment
Hope this helps. Looking forward to see how rails 6 is going to improve this

Running db:migrate kills the schema file

Every time I run rake db:migrate, my schema file is always changed to this
# A bunch of comments up here
ActiveRecord::Schema.define(version: WHATEVER_MY_LATEST_VERSION_IS) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
end
It will update the schema version, and run the migration. The tables will be created, indexes are created. It just leaves my schema.rb with nothing but this enable_extension in it. Running rake db:schema:dumpwill create the same schema file. I'm running on rails 4.1.10.
EDIT I do have the pg gem installed (0.18.1). There's no outstanding migrations. This app has been in production for over 2 years now. It's been doing this issue for the last year or so, but we only do a new migration maybe twice a year so we haven't put much effort in to it until now. My DB yml is pretty standard:
defaults: &defaults
encoding: utf8
adapter: postgresql
database: <%= ENV['DATABASE_NAME'] %>
username: <%= ENV['DATABASE_USERNAME'] %>
password: <%= ENV['DATABASE_PASSWORD'] %>
host: <%= ENV.fetch('DATABASE_HOST', 'localhost') %>
min_messages: WARNING
development:
<<: *defaults

Can't get PostGIS to work with Heroku / Rails - NoMethodError: undefined method `geography' / 'st_point'

I get these errors when trying to either migrate or db:schema:load on Heroku with Rails 5.0.1
Gemfile
# PostGIS adapter
gem 'activerecord-postgis-adapter'
database.yml
default: &default
adapter: postgis
encoding: unicode
pool: 5
postgis_extension: postgis
schema_search_path: public, postgis
production:
<<: *default
database: appname_production
username: appname
password: <%= ENV['APPNAME_DATABASE_PASSWORD'] %>
Migration
t.st_point :location, geographic: true, null: false
schema.rb
t.geography "location", limit: {:srid=>4326, :type=>"point", :geographic=>true}, null: false
Buildpacks
$ heroku buildpacks
=== appname-staging Buildpack URLs
1. https://github.com/cyberdelia/heroku-geo-buildpack.git
2. heroku/ruby
Running either heroku run rake db:migrate or heroku run rake db:schema:load gives NoMethodError: undefined method `st_point', NoMethodError: undefined method `geography', respectively. How can I fix this? What am I missing?
In case of that this will help someone i manged to solve the issue by using
production:
<<: *default
url: <%= ENV.fetch('DATABASE_URL', '').sub(/^postgres/, "postgis") %>
database: databasename_production
username: databasename
password: <%= ENV['databasename_DATABASE_PASSWORD'] %>
in my database.yml file
Have you tried changing the database url
https://github.com/rgeo/activerecord-postgis-adapter/issues/174

undefined method `geometry' for ActiveRecord::ConnectionAdapters::PostgreSQL

I have created a rails application using postgres database. I am using postgis extension for geo queries. The app is running successfully on my development(local) machine but after deploying my code on heroku server when I run heroku run rake db:migrate it is throwing an error, saying undefined method geometry for ActiveRecord ConnectionAdapters PostgreSQL.
I have geometry datatype in some migrations for storing latitude and longitude.
Note that I have also created PostGIS extension on heroku. And migrations that does not contain geometry datatype executed successfully.
My files are:
Gemfile
ruby "2.3.0"
gem 'rails', '>= 5.0.0.beta3', '< 5.1'
gem 'pg', '~> 0.18'
gem 'rgeo'
gem 'rgeo-activerecord', "~> 5.0.0.beta"
gem "activerecord-postgis-adapter", "~> 4.0.0.beta2"
psql --version is: 9.5.2 on heroku server
psql --version is: 9.4.7 on local server
database.yml
default: &default
adapter: postgis
encoding: unicode
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
development:
<<: *default
database: ad_development
production:
<<: *default
database: ad_production
username: ad
password: <%= ENV['DATABASE_PASSWORD'] %>
create_cities migration
def change
create_table :cities do |t|
t.string :name
t.references :state, foreign_key: true
t.geometry :lat_lan
end
heroku run rake db:migrate stops here only.
I am totally confused whether I have used inappropriate gems or I have misconfigured something. Please help!
If using the DATABASE_URL environment variable to set the database connection string, ensure it has the postgis:// (not postgres://) prefix.
ie. postgis://username:password#db_server_url:5432/dbname
url: <%= ENV.fetch('DATABASE_URL', '').sub(/^postgres/, 'postgis') %>
EDIT:
It replaces the url scheme postgres://somewhere.com to postgis://somewhere.com.
It changes to the GIS "protocol", like changing http to https.
You have to replace postgresql with postgis in your database.yml file for the adapter option.
E.g.
default: &default
adapter: postgis
encoding: unicode
pool: <%= ENV["DB_POOL"] || ENV['MAX_THREADS'] || 5 %>
url: <%= ENV['DATABASE_URL'] %>
development:
<<: *default
database: yourapp_development

undefined method `strong' when trying bundle exec rake db:migrate

I'm using Ruby 2.2.2 and Rails 4.2.3.
The commands I did are:
rails generate scaffold User name:string email:string
bundle exec rake db:migrate
The error I got is:
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
undefined method `strong' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x00000005b72028>/home/clemant/tutorials/test2/db/migrate/20150709221657_create_users.rb:5:in `block in change'
My migration file:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.strong :email
t.timestamps null: false
end
end
end
My database.yml file is:
# SQLite version 3.x
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
# gem 'sqlite3'
#
default: &default
adapter: sqlite3
pool: 5
timeout: 5000
development:
<<: *default
database: db/development.sqlite3
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *default
database: db/test.sqlite3
production:
<<: *default
database: db/production.sqlite3
Any idea how to fix this?
In your migration file, you have written: t.strong :email.
It should be rectified as follows:
t.string :email

Resources