Rails Heroku - Resetting the database - ruby-on-rails

I am trying to reset my database.
It isn't working locally or in heroku.
I succuessfully ran each of these commands:
1. rake db:drop
2. rake db:create
3. rake db:migrate
The migrations took a while to succeed. I commented out the ones that were causing a problem and the whole job finishes migrating.
I then try to reset my database with:
4. rake db:reset
I get this error:
initialize_schema_migrations_table()
-> 0.0031s
rake aborted!
NoMethodError: undefined method `name=' for #<University:0x007fc288bdcca0>
/app/vendor/bundle/ruby/2.2.0/gems/activemodel-4.1.9/lib/active_model/attribute_methods.rb:435:in `method_missing'
I can't find anywhere in the code base that has a method called 'name' for university. I have run searches looking for university.name and name near university.
I have updated my gems and run bundle install.
What does this error message mean?
When I try:
rake db:reset --trace
I get:
** Execute db:abort_if_pending_migrations
rake aborted!
NoMethodError: undefined method name=' for #<University:0x007f9a1b24da30>
/Users/em/.rvm/gems/ruby-2.2.2/gems/activemodel-4.1.9/lib/active_model/attribute_methods.rb:435:inmethod_missing'
I have run all migrations and refreshed rake db:migrate

This is the error you get when you are trying to write to a variable that you haven't declared an attr_writer for.
class Foo
attr_reader :bar
def initialize
#bar = 1
end
end
> f = foo.new
=> #<Foo:0xa22ef0c #bar=1>
> f.bar
=> 1
> f.bar = 2
NoMethodError: undefined method `bar=' for #<Foo:0xa22ef0c #bar=1>
from (irb):23
from /usr/local/rvm/rubies/ruby-2.1.3/bin/irb:11:in `<main>'

It looks like you've got something in your seeds.rb file causing the error.
The reason you're seeing the issue when running rake db:reset but not when running those 3 individual steps is because rake db:reset doesn't run those 3 individual steps.
rake db:reset will run the following:
rake db:drop
rake db:setup
and subsequently, rake db:setup will run these:
rake db:create
rake db:schema:load
rake db:seed
If you only want to do the initial 3 steps (rake db:drop, rake db:create, rake db:migrate), you can run this instead:
rake db:migrate:reset

Related

Obstacle with Ruby Rails Authentication

I am a brand new Ruby on Rails User
When I enter localhost:3000 ,
I get an error reading
Migrations are pending. To resolve this issue, run:
bin/rails db:migrate RAILS_ENV=development
You have 2 pending migrations:
20221119205559_add_devise_to_users.rb
20221119211811_drop_users_table.rb
# Raises <tt>ActiveRecord::PendingMigrationError</tt> error if any migrations are pending.
def check_pending!(connection = Base.connection)
raise ActiveRecord::PendingMigrationError if connection.migration_context.needs_migration?
end
def load_schema_if_pending!
In a nutshell, it was working before but I attempted to create a a basic authentication page(which was also working) , but for some reason when I clicked sign up I received an error also.
Thank you for any tips on how to fix this!
I have tried to
rake db:drop
rake db:create
rake db:migrate
Editing the migrate file with:
edit your migration file
class DropUsersTable < ActiveRecord::Migration
def change
drop_table :users
end
end
Then doing rake db:migrate
Also, I have run :
rails generate devise:install
rails generate devise User
bundle exec rake db:migrate

Rake db:seed rake aborted! ActiveRecord::RecordInvalid: Validation failed: Email has already been taken

I'm a beginning rails student at OneMonth learning stripe payments. Right now, I'm learning how to create a product table and seed the database. Everything's been smooth so far until I encountered a problem after running rake db: seed
Davids-MBP-2:one_month_stripe_payments DKP$ rake db:seed
rake aborted!
ActiveRecord::RecordInvalid: Validation failed: Email has already been taken
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/validations.rb:79:in raise_record_invalid'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/validations.rb:43:insave!'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/attribute_methods/dirty.rb:29:in save!'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/transactions.rb:291:inblock in save!'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/transactions.rb:351:in block in with_transaction_returning_status'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/connection_adapters/abstract/database_statements.rb:213:inblock in transaction'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/connection_adapters/abstract/transaction.rb:184:in within_new_transaction'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/connection_adapters/abstract/database_statements.rb:213:intransaction'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/transactions.rb:220:in transaction'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/transactions.rb:348:inwith_transaction_returning_status'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/transactions.rb:291:in save!'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/persistence.rb:51:increate!'
/Users/DKP/Desktop/one_month/one_month_stripe_payments/db/seeds.rb:8:in <top (required)>'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:inload'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in block in load'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:240:inload_dependency'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:268:in load'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/railties-4.2.5/lib/rails/engine.rb:547:inload_seed'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/tasks/database_tasks.rb:250:in load_seed'
/Users/DKP/.rvm/gems/ruby-2.3.0#global/gems/activerecord-4.2.5/lib/active_record/railties/databases.rake:183:inblock (2 levels) in '
/Users/DKP/.rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in eval'
/Users/DKP/.rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in'
Tasks: TOP => db:seed
(See full trace by running task with --trace)
I've tried rake db: reset, then rake:db migrate, then rake db: seed again. But i still have the same error.
Could anyone help me with this problem please? I'm feeling stuck and I'm not sure what to do.
Thanks so much!
When you do rake db:reset, what rails does is rake db:drop -> rake db:create -> rake db:migrate -> rake db:seed.
You DO NOT need to rake db:seed again.
you can check your console by doing rails c and see if you seed data is already inside. Product.all
'Email has already been taken' means you have a record with the same email already present.
Do Rails console and check if the records are there or not.
If not, do rake db:drop -> rake db:create -> rake db:migrate -> rake db:seed. This will solve your problem.

PG::UndefinedTable: ERROR: table "table-name" does not exist

I was messing with my database, creating and deleting tables. I deleted few migration files after pushing them to heroku. Previously I created a table 'moms'. Later I wanted to rename it, so I deleted 'moms' and created new table 'minutes_of_meetings'. I did $rake db:migrate and everything was done successfully and my app is running perfectly on localhost.
After pushing it to heroku, when I did $heroku run rake db:migrate, it generated the following log:
ActiveRecord::SchemaMigration Load (0.7ms) SELECT "schema_migrations".* FROM "schema_migrations"
Migrating to DropMoms (20150823142852)
(0.6ms) BEGIN
== 20150823142852 DropMoms: migrating =========================================
-- drop_table(:moms)
(0.9ms) DROP TABLE "moms"
PG::UndefinedTable: ERROR: table "moms" does not exist
: DROP TABLE "moms"
(0.5ms) ROLLBACK
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedTable: ERROR: table "moms" does not exist
: DROP TABLE "moms"/app/vendor/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `async_exec'
/app/vendor/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/connection_adapters/postgresql/database_statements.rb:155:in `block in execute'
I created a new table 'moms' in heroku so that it can be deleted when migration runs. I did this:
$ heroku run Ruby console for rails-app-name >> ActiveRecord::Migration.create_table :moms
I also created a migration to create table 'moms'. But still the error persists.
EDIT:
This is my CreateMoms migration file:
class CreateMoms < ActiveRecord::Migration
def change
create_table :moms do |t|
t.string :name
t.timestamp null: false
end
end
end
When I run heroku run rake db:migrate:up
Running `rake db:migrate:up` attached to terminal... up, run.1729
rake aborted!
VERSION is required
/app/vendor/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/railties/databases.rake:78:in `block (3 levels) in <top (required)>'
Tasks: TOP => db:migrate:up
(See full trace by running task with --trace)
WARNING: Toolbelt v3.41.3 update available.
On heroku run rake db:migrate:down
Running `rake db:migrate:down` attached to terminal... up, run.6389
rake aborted!
VERSION is required - To go down one migration, run db:rollback
/app/vendor/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/railties/databases.rake:86:in `block (3 levels) in <top (required)>'
Tasks: TOP => db:migrate:down
(See full trace by running task with --trace)
WARNING: Toolbelt v3.41.3 update available.
Caution
rake db:schema:load will wipe away all of your data from the heroku database. Please make sure you have your data backup on heroku. If you already don't have backup of your heroku database, you can easily do so by using Heroku PGBackups
Looks like your schema is messed up. Just load the schema to the database using rake db:schema:load and then run the migration again:
heroku run rake db:schema:load
heroku run rake db:migrate

Heroku, cron.rake and friendly_id gem

I'm using the friendly_id gem.
There's a rake task for deleting old slugs (from the docs):
rake friendly_id:remove_old_slugs MODEL=<model name> DAYS=<days>
It can be run via cron.
Do you know how it should be added to cron.rake (I'm on Heroku)?
Here is my cron.rake:
desc "This task is called by the Heroku cron add-on"
task :cron => :environment do
...
rake friendly_id:remove_old_slugs
end
It produces an error:
"rake aborted! undefined method `friendly_id' for main:Object"
There is no error if I run it from the console (Terminal) like this:
heroku rake friendly_id:remove_old_slugs
Try this:
desc "This task is called by the Heroku cron add-on"
task :cron => :environment do
Rake::Task['friendly_id:remove_old_slugs'].execute
end

Execute a Rake task from within migration?

I have a Rake task that loads configuration data into the DB from a file, is there a correct ruby/rails way to call it on a migration up?
My objective is to sync my team DB configs, without have to broadcast then to run the task lalala
def self.up
change_table :fis_situacao_fiscal do |t|
t.remove :mostrar_endereco
t.rename :serie, :modelo
end
Faturamento::Cfop.destroy_all()
#perform rake here !
end
UPDATE
How I do now, and works:
system('rake sistema:load_data file=faturamento/cfop')
And this is the suggestion from #Ryan Bigg, and it's exception:
Rake::Task['rake sistema:load_data file=faturamento/cfop'].invoke()
.
== AlterSituacaoFiscalModeloEndereco: migrating ====================
-- change_table(:fis_situacao_fiscal)
-> 0.0014s
rake aborted!
An error has occurred, this and all later migrations canceled:
Don't know how to build task 'rake sistema:load_data file=faturamento/cfop'
Where it went wrong?
Yes there's a way to do that:
Rake::Task['your_task'].invoke
Update
Do not put rake inside the brackets, just the name of the task. You should set an ENV variable when running this:
In the console
FILE=somefile.text rake db:sistema:load_data
Calling it separately
FILE=somefile.text rake some:other:task:that:calls:it
This will be available in your tasks as ENV['file']
Note that if you call the Rake task with 'system', you need to check the process status afterwards and raise an exception if the Rake task failed. Otherwise the migration will succeed even if the Rake task fails.
You can check the process status like this:
if !($?.success?)
raise "Rake task failed"
end
Invoking the rake task is a nicer option - it will cause the migration to fail if the Rake task fails.
You can execute a rake task from within a loaded Rails environment with either Rake::Task['namespace:task'].invoke or Rake::Task['namespace:task'].execute.
You can pass data to the task inside of the invoke or execute method. Example:
Rake::Task['namespace:task'].invoke(paramValue)
This param can be handled in the rake task as follows:
namespace :namespace do
desc "Example description."
task :task, [:param] => :environment do |t, args|
puts args[:param]
...
end
end
This can be executed on the console as:
bundle exec rake namespace:task[paramValue]
More info: https://medium.com/#sampatbadhe/rake-task-invoke-or-execute-419cd689c3bd
This decision fits better, IMHO.
In your case it would be smth like this:
backup_env = ENV.slice('file') if ENV.key?('file')
ENV['file'] = 'faturamento/cfop'
Rake::Task['sistema:load_data'].invoke
ENV.delete 'file'
ENV.merge!(backup_env) if backup_env

Resources