Migration in Rails gives back could not find table error - ruby

I made a new migration in order to add a price column in my Ingredients Active Record. Despite that when I run rails db:migrate I get an error saying that the table ingredients does not exist. Here are my console commands:
C:\Users\andri\Desktop\hoagieShop\hoagieShop>rails generate migration
AddPriceToIngredients price:decimal, false:null --force
invoke active_record
remove db/migrate/20190124075954_add_price_to_ingredients.rb
create db/migrate/20190124080657_add_price_to_ingredients.rb
C:\Users\andri\Desktop\hoagieShop\hoagieShop>rails db:migrate
== 20190123201200 RemovePriceFromIngrendients: migrating
======================
-- remove_column(:ingrendients, :price, :decimal)
rails aborted!
StandardError: An error has occurred, this and all later migrations
canceled:
Could not find table ingrendients
C:/Users/andri/Desktop/hoagieShop/hoagieShop/db/migrate/201901232
01200_remove_price_from_ingrendients.rb:3:in change
bin/rails:4:in require
bin/rails:4:in <main>
Caused by:
ActiveRecord::StatementInvalid: Could not find table ingrendients
C:/Users/andri/Desktop/hoagieShop/hoagieShop/db/migrate/20190123201200_
remove_pr
ice_from_ingrendients.rb:3:in change
bin/rails:4:in require
bin/rails:4:in <main>
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
I have removed and added this migration again a few times so I am not sure if this plays any role.
Does anyone have an idea as to why this happens? I appreciate any help!

This seems to be a simple typo in your 20190123201200_remove_price_from_ingrendients.rb migration, and not in the migrations you've generated, see:
-- remove_column(:ingrendients, :price, :decimal)
It should probably be ingredients not ingrendients (extra n before dients)

Related

Hanami rake task does not load repositories

I have hanami 1.3.0 app named booking. There is rake task in /rakelib/motel.rake :
require_relative '../lib/booking' # it requires booking/motel/booker file
namespace :motel do
task :book do
Booking::Motel::Booker.new.book
end
end
booking/motel/booker requires booking_repository file, and tries to instantiate BookingRepository, but fails with error:
NameError: uninitialized constant Hanami::Repository
<root>/lib/booking/repositories/booking_repository.rb:1:in <top (required)>'
However, when I run Booking::Motel::Booker.new.book in hanami console, it loads BookingRepository without problems.
Looked at numerous stack questions regarding hanami rake, but couldn't find an answer.
As it turns out, it was a foolish mistake. I forgot to add :environment to my task.
namespace :motel do
task book: :environment do
Booking::Motel::Booker.new.book
end
end
That fixed it and dropped the need to use manual file loading, of course.

"padrino rake sq:migrate -e development"doesn't update collection

I would like to add one more field to accounts table.
So I have done this
1) padrino g migration AddPhoneNumberToAccounts phone_number:string
This make a migration file named
038_add_phone_number_to_accounts.rb
2) and I migrated.
padrino rake db:migrate -e development
But it make errors
/Users/whitesnow/.rvm/gems/ruby-2.4.1/gems/sequel-4.46.0/lib/sequel/extensions/migration.rb:601:in `block in get_migration_files': Missing migration version: 6 (Sequel::Migrator::Error)
from /Users/whitesnow/.rvm/gems/ruby-2.4.1/gems/sequel-4.46.0/lib/sequel/extensions/migration.rb:601:in `upto'
from /Users/whitesnow/.rvm/gems/ruby-2.4.1/gems/sequel-4.46.0/lib/sequel/extensions/migration.rb:601:in `get_migration_files'
....
How to solve this? sometimes I didn't get this errors but it doesn't update table either.
Thanks.

ActiveRecord::NoEnvironmentInSchemaError

I'm trying to perform database related operations on my newly upgraded app(Rails 5) and I'm unable to perform destructive database commands locally.
rails db:reset or rails db:drop .
The trace results with the following data,
rails db:drop --trace
** Invoke db:drop (first_time)
** Invoke db:load_config (first_time)
** Execute db:load_config
** Invoke db:check_protected_environments (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config
** Execute db:check_protected_environments
rails aborted!
ActiveRecord::NoEnvironmentInSchemaError:
Environment data not found in the schema. To resolve this issue, run:
bin/rails db:environment:set RAILS_ENV=development
What I've tried so far are,
Setting bin/rails db:environment:set RAILS_ENV=development, doesn't change anything still the error occurs.
Setting Environment variable manually to development.
None of these helped. I'm Looking for a fix or workaround.
Two Fixes to ActiveRecord::NoEnvironmentInSchemaError
The other answers here describe the problem very well, but lack proper solutions. Hoping this answer helps someone experiencing this issue.
Why this error is happening
This incorrect error message is a result of this pull request designed to prevent destructive actions on production databases. As u/pixelearth correctly points out, Rails 4.2 defines the 'key' field in the ar_internal_metadata table to be an integer, and Rails 5+ (including Rails 6) expects this to be a string with the value, environment. When Rails 5 and Rails 6 run this safety check, they incorrectly raise an ActiveRecord::NoEnvironmentInSchemaError as the code is incompatible with the Rails 4 schema format.
Fix #1: Override the safety check in Rails 5+
**Please remember, the safety check was implemented as a result of so many users dropping their production databases by accident. As the question describes, the operations are destructive.
From the terminal:
rails db:drop RAILS_ENV=development DISABLE_DATABASE_ENVIRONMENT_CHECK=1
# and/or
rails db:drop RAILS_ENV=test DISABLE_DATABASE_ENVIRONMENT_CHECK=1
As noted here, the DISABLE_DATABASE_ENVIRONMENT_CHECK=1 flag disables the environment check. After, you can run a rake db:create RAILS_ENV=development, for example, to recreate your database with the correct schema in the ar_internals_metadata table.
Fix #2: Revert to Rails 4, drop database, go back to Rails 5+ and recreate
From the terminal:
git log
# grab the commit hash from before the upgrade to Rails 5+
git checkout **hash_from_rails_4**
rake db:drop RAILS_ENV=development
rake db:drop RAILS_ENV=test
git checkout master
# now things should work
rails db:migrate
Again, please ensure you are not pointing at a production database when overriding this functionality. Alternatively, it would be possible to directly modify the schema of this table. If you're experiencing this error in production, you may need to take this approach.
This happened because, for some reason, your table ar_internal_metadata got deleted or changed.
If you cannot drop the database via the command line, you need to do it via your DBMS or database client.
Then, just run rails db:create db:migrate to create and run the migrations.
For posterity, my issue was that this schema was generated by a rails 4 app and the current app using it is rails 5. With rails 5 the structure of the ar_internal_metadata table has changed slightly. The key field needs to be a string and contain the word 'environment', not an integer. This error only goes away when this is changed.
It should look like this in Rails 5
ie, change the type of ar_internatl_metadata #key to string...
My situation is a bit uncommon involving a rails 4 app and a rails 5 app sharing the same db. When I need to "update", I have a task:
puts "Modifying Rails 4 schema to fit Rails 5 schema"
file_name = "./db/schema.rb"
rails_4_ar_internal_metadata = 'create_table "ar_internal_metadata", primary_key: "key", force: :cascade do |t|'
rails_5_ar_internal_metadata = 'create_table "ar_internal_metadata", primary_key: "key", id: :string, force: :cascade do |t|'
new_schema = File.read(file_name).gsub(rails_4_ar_internal_metadata, rails_5_ar_internal_metadata)
File.write(file_name, new_schema)
Console rails
bin/rails db:environment:set RAILS_ENV=development
I had
bundle exec rake db:drop
rake aborted!
ActiveRecord::NoEnvironmentInSchemaError:
Environment data not found in the schema. To resolve this issue, run:
rails db:environment:set RAILS_ENV=development
And, indeed, simply running rails db:environment:set RAILS_ENV=development made the problem go away.
Why did this happen?
It happened because I tried to drop the database and create it / migrate it, however, I had a syntax error in the migration (datatype and column name in the wrong places). Check your migration file for any silly errors
Specifically I had
t.submitted :boolean, default: false
instead of
t.boolean :submitted, default: false

Ruby Rake ActiveRecord Migrate

I'm trying to build a simple ruby script that connects to a database and runs some basic queries.
The code is here: https://github.com/mastermindg/rack-activrecord-example
It's not a service - only a script that is run manually to do batch jobs. My problem is that I need to populate the database for testing purposes. I know how to do this in Sinatra and Rails but it's failing as-is:
NoMethodError: undefined method `set' for main:Object
Did you mean? send
/usr/src/app/app.rb:7:in `<top (required)>'
/usr/src/app/Rakefile:2:in `<top (required)>'
I've got the database.yml but I can't tell how to load it since set is failing.
How do I connect to and query a database using ActiveRecord with basic Rack?
1) Add this to your Rakefile after the requires:
DatabaseTasks.database_configuration = YAML.load(File.read(File.join(root, 'config/database.yml')))
2) Remove set :database_file, 'config/database.yml' from your app.rb file (I think set is a sinatra/activerecord method).
Running rake db:create may give you an error on your project now,because you're using json instead of JSON in your app.rb file (depending on your local versions), so. . .
3) Change puts json Resource.select('id', 'name').all to puts JSON Resource.select('id', 'name').all in your app.rb file.
Now rake db:create will throw a database error, but that's an error related to your specific database configuration, make an appropriate adjustment to that (this is off-topic from the original question, so I won't address it further) and your app should run as you desire.
More info:
This gist shows example contents of a Rakefile that you could use to run Active Record tasks without using Rails or Sinatra.

Spree commerce spree taxonomies error

I'm trying to run my spree commerce project (2.0), but when I excute the command
rails server, this message is displayed
ActiveRecord::StatementInvalid in Spree/home#index
Showing
/home/iron/.rvm/gems/ruby-1.9.3-p392/gems/spree_frontend-2.0.1/app/views/spree/shared/_taxonomies.html.erb
where line #2 raised:
Could not find table 'spree_taxonomies' Extracted source (around line #2):
1: <nav id="taxonomies" class="sidebar-item" data-hook>
2: <% get_taxonomies.each do |taxonomy| %>
3: <h6 class='taxonomy-root'><%= Spree.t(:shop_by_taxonomy, :taxonomy => taxonomy.name) %></h6>
4: <%= taxons_tree(taxonomy.root, #taxon, Spree::Config[:max_level_in_taxons_menu] || 1) %>
5: <% end %>
Error occurs because database table spree_taxonomies doesn't exist.
You should run rake db:migrate in order to create database and tables.
Dont forget to be doing it on the production environment
rake db:migrate RAILS_ENV=production
rake assets:precompile RAILS_ENV=production
Looks like spree_taxonomies table is missing. You need to
run rake db:migrate
On Production - RAILS_ENV=production rake db:migrate
All the above answers should solve the problem.
I would just like to note there is a best practice when developing applications in rails.
Add a bin/setup file which does all the grunt work for you.
This solves the problem of remembering all the tasks you have to do when starting on a project.
Just execute bin/setup and your done.
Source:
http://robots.thoughtbot.com/bin-setup

Resources