Why is this Rails migration giving a 'no such table' error? - ruby-on-rails

In a new Rails 6 project, I have a table named object_classes with a column named ClassList_id. From schema.rb:
create_table "object_classes", force: :cascade do |t|
t.string "name"
t.integer "ClassList_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["ClassList_id"], name: "index_object_classes_on_ClassList_id"
end
I've realized that the column should be named class_list_id to conform with Rails expected naming convention. Therefore, I have generated a new migration:
class FixColumnName < ActiveRecord::Migration[6.0]
def change
rename_column :object_classes, :ClassList_id, :class_list_id
end
end
However, when I run this migration, I get the following error:
/bin/bash -c "env RBENV_VERSION=2.6.1 /home/asfarley/.rbenv/libexec/rbenv exec bundle exec ruby /home/asfarley/imgseq/bin/spring rails 'db:migrate'"
== 20200716060501 FixColumnName: migrating ====================================
-- rename_column(:object_classes, :ClassList_id, :class_list_id)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: no such table: main.ClassLists
/home/asfarley/imgseq/db/migrate/20200716060501_fix_column_name.rb:3:in `change'
/home/asfarley/imgseq/bin/rails:9:in `<top (required)>'
/home/asfarley/imgseq/bin/spring:15:in `require'
/home/asfarley/imgseq/bin/spring:15:in `<main>'
Caused by:
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: main.ClassLists
/home/asfarley/imgseq/db/migrate/20200716060501_fix_column_name.rb:3:in `change'
/home/asfarley/imgseq/bin/rails:9:in `<top (required)>'
/home/asfarley/imgseq/bin/spring:15:in `require'
/home/asfarley/imgseq/bin/spring:15:in `<main>'
Caused by:
SQLite3::SQLException: no such table: main.ClassLists
/home/asfarley/imgseq/db/migrate/20200716060501_fix_column_name.rb:3:in `change'
/home/asfarley/imgseq/bin/rails:9:in `<top (required)>'
/home/asfarley/imgseq/bin/spring:15:in `require'
/home/asfarley/imgseq/bin/spring:15:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
Process finished with exit code 1
What am I doing wrong here? I'm looking for an explanation that addresses specifically what is wrong here, so that I can understand how to avoid this in the future.

Hard to know whether the fault is Rails or SQLite, but the issue seems to be that I had a foreign key defined for my object_classes table pointing to a table that didn't exist. With this migration, I was able to fix the foreign key constraint and rename the column:
class FixColumnName < ActiveRecord::Migration[6.0]
def change
remove_foreign_key :object_classes, :ClassLists
rename_column :object_classes, :ClassList_id, :class_list_id
add_foreign_key :object_classes, :class_lists
end
end

your syntax is ok so the error must be a reserved name error. may try and remove the column and creating the column again, watch out for capital letters on migrations for they can unnecessarily complicate your code. try this:
rails g migration RemoveClassListIdFromObjectClasses
that will created a migration kinda like this:
def drop
remove column :object_classes, :class_lis_id
end
and then run
rails g migration AddClassListIdToObjectClasses
the migration should look something like this:
def change
add_column :object_classes, :class_list_id
end
remember to add the data type and anything else you may need.
there you can check the migration it created and you can change it to maybe add the data type or maybe change the capitalization of the column and you will be set to go.
note: if it works i would appreciate if you accepted the answer, Thanks!

Related

Specified key was too long while migrating

class CreateUsers < ActiveRecord::Migration[6.0]
def change
create_table :users do |t|
t.string :user
t.timestamps
end
end
end
class CreateArticles < ActiveRecord::Migration[6.0]
def change
create_table :articles do |t|
t.string :content
t.timestamps
end
end
end
I created these two entities in a new project and when I run migrate I get this error:
rails db:setup
Created database 'rails_api_development'
Created database 'rails_api_test'
C:/Users/admin/Desktop/projects/rails-api/db/schema.rb doesn't exist yet. Run `rails db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter C:/Users/admin/Desktop/projects/rails-api/config/application.rb to limit the frameworks that will be loaded.
admin#Desktop MINGW32 ~/Desktop/projects/rails-api (master)
$ rails db:migrate
rails aborted!
ActiveRecord::StatementInvalid: Mysql2::Error: Specified key was too long; max key length is 1000 bytes
bin/rails:4:in `require'
bin/rails:4:in `<main>'
Caused by:
Mysql2::Error: Specified key was too long; max key length is 1000 bytes
bin/rails:4:in `require'
bin/rails:4:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
Also, why does it say mysql2 even though I entered mysql as the database? What the heck is wrong with rails? Is it a problem with the ORM or some other config issues?
SET GLOBAL default_storage_engine = 'InnoDB';
Running this in phpmyadmin solved it. Seems to be an issue with MySQL database.

No implicit conversion of Array into String - Rails Migration

Trying to get an app up and running on a new machine. May be using a slightly updated version of Ruby (2.3.4 vs 2.3.1) and the Rails version is 5.1.3.
Here's the migration:
class AddDragAndDropRules < ActiveRecord::Migration[5.0]
def change
add_column :products, :fixture_location, :string, default: "none"
add_column :products, :attaches_to, :uuid, array: true, default: []
end
end
The issue during rails db:migrate.
Error:
== 20160928162420 AddDragAndDropRules: migrating ==============================
-- add_column(:products, :fixture_location, :string, {:default=>"none"})
-> 0.0142s
-- add_column(:products, :attaches_to, :uuid, {:array=>true, :default=>[]})
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:
no implicit conversion of Array into String
/Users/mike/api/db/migrate/20160928162420_add_drag_and_drop_rules.rb:4:in `change'
bin/rails:9:in `require'
bin/rails:9:in `<main>'
TypeError: no implicit conversion of Array into String
/Users/mike/api/db/migrate/20160928162420_add_drag_and_drop_rules.rb:4:in `change'
bin/rails:9:in `require'
bin/rails:9:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
Anyone able to spot the error?
In case this helps anyone else - the project was upgraded to Rails 5.1.3 at some point which is causing UUID array migrations to fail due to a bug.
Issue is here (https://github.com/rails/rails/issues/30539) and workaround in 5.1.2-5.1.3 is to do this:
add_column :products, :attaches_to, :uuid, array: true, default: '{}'
Should be fixed in 5.1.4 and above.

Error ActiveRecord::PendingMigrationError

I am following Michael Hartl's book and I am getting this error when I run the server:
I am getting ActiveRecord::PendingMigrationError when I run the server, this shows up:
Migrations are pending. To resolve this issue, run: bin/rails db:migrate RAILS_ENV=development
Please I've been stuck in this error for so long.
When I type $ RAILS_ENV=development rake db:migrate I get this error:
== 20161209073230 AddActivationToUsers: migrating =============================
-- add_column(:users, :activation_digest, :string) rake aborted! StandardError: An error has occurred, this and all later migrations
canceled:
SQLite3::SQLException: duplicate column name: activation_digest: ALTER
TABLE "users" ADD "activation_digest" varchar
(required)>' Tasks: TOP => db:migrate (See full trace by running task
with --trace)
test/mailers/previews/user_mailer_preview.rb
UserMailerPreview < ActionMailer::Preview
# Preview this email at
http://localhost:3000/rails/mailers/user_mailer/account_activation
def account_activation
user = User.first
user.activation_token = User.new_token
UserMailer.account_activation(user) end
# Preview this email at
http://localhost:3000/rails/mailers/user_mailer/password_reset def
password_reset
UserMailer.password_reset end
end
Schema.rb:
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20161123005710) do
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.string "remember_digest"
t.string "activation_digest"
t.index ["email"], name: "index_users_on_email", unique: true end
end
Latest migration is
db/migrate/[timestamp]_add_activation_to_users.rb:
class AddActivationToUsers < ActiveRecord::Migration[5.0]
def change
add_column :users, :activation_digest, :string
add_column :users, :activated, :boolean, default: falserao
add_column :users, :activated_at, :datetime
end
end
The correct command to apply unapplied migrations is RAILS_ENV=development rake db:migrate
This just means that you have a migration pending. When you create a new migration
railas g migration MigrationName
it means that it changes something in the database schema or the layout of your database. In order to commit that change, you have to run:
bin/rails db:migrate
This will look into your migration file and apply it to your databse. Once the migration is done, you can run server as usual again.
rails server
If you have more question, I recommend reading the migration documentation that Rails published:
http://guides.rubyonrails.org/active_record_migrations.html
SQLite3::SQLException: duplicate column name: activation_digest:
(The following is the SQL command that actually modifies the db):
ALTER TABLE "users" ADD "activation_digest"
The SQL command reads like plain English. Somehow one of your migrations is doing something a previous migration already did, namely adding the activation_digest column to your users table in the db. If you look in the directory db/migrate/, you will see all your migration files. If you open one of them up, you should sort of be able to tell what it is doing. So look at all your migration files and find the two migrations that both add the activation_digest column. If the two migration files are identical, then you need to delete one--but take the following steps before deleting a migration:
https://www.baserails.com/questions/i-messed-up-while-generating-my-migration-how-can-i-undo-it
Also check out the section Rolling Back in the Rails Guide:
http://edgeguides.rubyonrails.org/active_record_migrations.html#reverting-previous-migrations
If for some reason you don't have two identical migration files that both add the activation_digest column, e.g one of the migration files does something additionally, then you need to figure out what steps in the tutorial that you did wrong, then rollback to the last migration that you know is correct. Finally, follow the steps in the tutorial again for generating the subsequent migrations.
It seems your users table already have a column named activation_digest. Remove the add_column line where the column is added from the migration file and run the migration again.
I think this migration file should work:
class AddActivationToUsers < ActiveRecord::Migration[5.0]
def change
add_column :users, :activated, :boolean, default: false
add_column :users, :activated_at, :datetime
end
end
Ok the answer is very simple!Just try migrating your DB to version=0 with command: rake db:migrate VERSION=0
and then run rake db:migrate

Why am I getting: Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=development

I am a total newbie to Rails, and I am following the Railsbridge Intro to Rails. I have created my project and now I am trying to create a new controller action for voting, and a new route for voting. When I go to the development page, it shows the following message:
Migrations are pending. To resolve this issue, run: bin/rake
db:migrate RAILS_ENV=development
In the command line it gives me this information:
StandardError: An error has occurred, this and all later migrations canceled:
undefined method `migrate' for #<ActiveRecord::ConnectionAdapters::TableDefiniti
on:0x5d79e78>C:/Sites/railsbridgejan/suggestotron/db/migrate/20150129195744_create_votes.rb:6:in `block in change' C:/Sites/railsbridgejan/suggestotron/db/migrate/20150129195744_create_votes.rb:3:in `change'
C:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
So, when I look in my db files for create_votes.rb this is what it looks like:
class CreateVotes < ActiveRecord::Migration
def change
create_table :votes do |t|
t.integer :topic_id
t.string :rake
t.migrate :db
t.timestamps null: false
end
end
end
Is there something wrong with my file's code? t.migrate :db is line 6, which according to the command line, is the problem. I am using Rails 4, Ruby 2, and Sqlite. I had tried to install MySql, but I ran into some major issues, so I just continued with Sqlite. Could that be causing this problem at all? It seems like the issue is in the code listed above, but I'm not sure.
Thank you!
Inside the change method you use
t.migrate :db
The migrate data type doesn't exist. I assume you wanted to use a String.
t.string :db

Ruby on Rails: rake db:migrate error after running scaffold

Have a little issue going on, not too sure what I've done but I just created a rails application followed by these commands.
I ran:
rails generate scaffold Post heading body:text price:decimal neighborhood external_url timestamp
in my terminal followed by:
rake db:migrate
Next I get an error that reads:
== 20150108012341 CreatePosts: migrating ======================================
-- create_table(:posts)
-> 0.0021s
== 20150108012341 CreatePosts: migrated (0.0022s) =============================
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
wrong number of arguments (1 for 0)/Users/taimurknaziri/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0.beta2/lib/active_record/connection_adapters/abstract_adapter.rb:271:in `initialize'
/Users/taimurknaziri/.rvm/gems/ruby-2.1.1/gems/activerecord-
...
4.2.0.beta2/lib/active_record/tasks/database_tasks.rb:135:in `migrate'
/Users/taimurknaziri/.rvm/gems/ruby-2.1.1/gems/activerecord-4.2.0.beta2/lib/active_record/railties/databases.rake:44:in `block (2 levels) in <top (required)>'
/Users/taimurknaziri/.rvm/gems/ruby-2.1.1/bin/ruby_executable_hooks:15:in `eval'
/Users/taimurknaziri/.rvm/gems/ruby-2.1.1/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
Migration file:
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :heading
t.text :body
t.decimal :price
t.string :neighborhood
t.string :external_url
t.string :timestamp
t.timestamps null: false
end
end
end
This is what the command should be
rails generate scaffold Post heading:string body:text price:decimal neighbourhood:string externalurl:string timestamp:string
You should be mentioning the data types for all the fields .
The problem was in my gem file, my rails version was rails 4.2 beta 2. I found the solution here:
Can't migrate database after scaffold. Section 2.2 Ruby on Rails Tutorial Michael Hartl
I had to add the gem arel and run bundle update arel followed by bundle install.

Resources