How to completely remove a model and its associations in Rails? - ruby-on-rails

Description
I'm on Ruby version 2.6.6 and Ruby on Rails version 6.0.3.2.
Models
Book
Author
Associations
A Book belongs to an Author.
An Author has many Books.
Goal
Remove the Author model and add it as a column to a Book (of type string).
What I've Done
I created and ran 3 migrations, in the following order:
AddAuthorToBooks
class AddAuthorToBooks < ActiveRecord::Migration[6.0]
def change
add_column :books, :author, :string
end
end
DropAuthors
class DropAuthors < ActiveRecord::Migration[6.0]
def change
drop_table :authors do |t|
t.string "full_name", null: false
t.timestamps null: false
end
end
end
RemoveAuthorForeignKeyFromBooks
class RemoveAuthorForeignKeyFromBooks < ActiveRecord::Migration[6.0]
def change
remove_foreign_key :books, :authors
end
end
Schema
Unfortunately, I don't have the schema before I ran the migrations. (I tried checking out an older commit, but the schema file stubbornly refuses to change.)
Here is the current version:
ActiveRecord::Schema.define(version: 2020_08_11_125724) do
create_table "books", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "cover_url"
t.decimal "price"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.integer "author_id", null: false
t.string "author"
t.index ["author_id"], name: "index_books_on_author_id"
end
create_table "books_genres", id: false, force: :cascade do |t|
t.integer "book_id", null: false
t.integer "genre_id", null: false
t.index ["book_id", "genre_id"], name: "index_books_genres_on_book_id_and_genre_id"
t.index ["genre_id", "book_id"], name: "index_books_genres_on_genre_id_and_book_id"
end
create_table "genres", force: :cascade do |t|
t.string "name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "reviews", force: :cascade do |t|
t.string "username"
t.decimal "rating"
t.text "body"
t.integer "book_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["book_id"], name: "index_reviews_on_book_id"
end
add_foreign_key "reviews", "books"
end
Problem
The author table has been removed, the add_foreign_key "books", "authors" (I think that's how it went) is gone, too, but the author_id stubbornly remains in the books table.
Furthermore, there's an integer author_id and an index of the same name.
What I'm Planning
I thought of just deleting these 2 columns with another migration, but I don't know if that would...
...fix the issue and erase the old Author model completely,
...and that it's the clean/recommended way of doing things. If needed, I could roll back the migrations and try a better method.

About the unusual `schema.rb` behavior
I tried checking out an older commit, but the schema file stubbornly refuses to change.
This is quite unusual. Do verify that you're tracking the db/schema.rb file using git. If it is tracked, there's no reason why checking out an older commit shouldn't return it to the older state. At that point, you should be able to:
$ rails db:drop
$ rails db:create
$ rails db:schema:load
...to load the old schema into the database. Then, you should be able to return to the latest code with git, and run pending migrations after the date at which the older schema was created.
About a cleaner way to implement this
Before writing the below migration, the first step would be to remove any existing relationship written in the Book class. For example:
# app/models/book.rb
class Book < ApplicationRecord
# The line below should be deleted! Otherwise, it will probably interfere
# with the `book.update!(author: ...)` line in the migration.
belongs_to :author
end
I've taken to writing related migrations in a single file, since they're all related. To me, this looks like:
class MoveAuthorToBooks < ActiveRecord::Migration[6.0]
class Author < ApplicationRecord
end
class Book < ApplicationRecord
end
def up
# Start by adding a string column.
add_column :books, :author, :string
# Let's preserve existing author names.
Book.all.each do |book|
author = Author.find(book.author_id)
book.update!(author: author.name)
end
# Now that the names have been moved to the books table, we don't
# need the relationship to `authors` table anymore. This should
# also delete any related foreign keys - manual foreign key deletion
# should not be required.
remove_column :books, :author_id
# Alternative: If you'd created the `authors_id` column using the
# `add_reference` command, then it's probably best to use the opposite
# `remove_reference` command.
#
#remove_reference :books, :author, index: true, foreign_key: true
# Finally, remove the `authors` table.
drop_table :authors
end
def down
# This can be technically be reversed, but that'll need some more code that
# reverses the action of the `up` function, and it may not be needed.
raise ActiveRecord::IrreversibleMigration
end
end

Related

Rails array transfer to new join table

I have a table Exercise and I'm transferring arrays from a column, dynamic, to a new join table ExerciseDynamicMuscle. This way each :id in the array becomes it's own object/record. I've tested it and it works or at least when checking the records it has transferred correctly, I'm just curious if there is anything else I should add or look out for?
Migration info for table being transferred to:
create_table :exercise_dynamic_muscles do |t|
t.belongs_to :exercise
t.belongs_to :muscle
t.timestamps
end
Migration created to do the transfer:
Exercise.find_each do |e|
e.dynamic.each do |mu|
ExerciseDynamicMuscle.create(
muscle_id: mu,
exercise_id: e.id
)
end
end
The ExerciseDynamicMuscle schema:
create_table "exercise_dynamic_muscles", force: :cascade do |t|
t.bigint "exercise_id"
t.bigint "muscle_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["exercise_id"], name: "index_exercise_dynamic_muscles_on_exercise_id"
t.index ["muscle_id"], name: "index_exercise_dynamic_muscles_on_muscle_id"
end
Once the data is transferred I plan to drop the columns via another migration:
remove_column :exercises, :dynamic
So there will be two separate migrations:
One to transfer the data
One to drop the columns
Usually migrations are reversible. To do that, you need something like
def up
create_table :exercise_dynamic_muscles do |t|
t.belongs_to :exercise
t.belongs_to :muscle
t.timestamps
end
Exercise.find_each do |e|
e.dynamic.each do |m_id|
ExerciseDynamicMuscle.create!(
muscle_id: m_id,
exercise_id: e.id
)
end
end
remove_column :exercises, :dynamic
end
def down
change_table :exercises do |t|
t.text :dynamic, array: true, default: []
end
ExerciseDynamicMuscle.find_each do |edm|
exercise = edm.exercise
exercise.dynamic << edm.muscle_id
exercise.save!
end
drop_table :exercise_dynamic_muscles
end
Firstly you create new table, than migrate data to this table from array columns, and finally drop array column
Rollback migration is everything the same but in reverse order only

When I run rails db:migrate the migration doesn't fully work

class CreateMessages < ActiveRecord::Migration[5.2]
def change
create_table :messages do |t|
t.text :body
t.integer :user_id
t.timestamps
end
end
end
After running rails db:migrate my schema looks like this...
ActiveRecord::Schema.define(version: 2020_03_20_063104) do
create_table "messages", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "password_digest"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
I am wondering where the t.text "body" is and where the t.integer "user_id"is and why it isn't showing up in my schema under messages table.
I have checked migration status and all migrations have been ran.
If you ran something like this in your migration file
class CreateMessages < ActiveRecord::Migration[5.2]
def change
create_table :messages do |t|
t.timestamps
end
end
end
Messages table is created and after this you can't create another migration with create_table :messages. Like #Marek Lipka wrote on comments. Either you need to rollback your CreateMessages migration and chance file and run your migration again. Or you need to write another migration to change existing table like this.
class AddBodyAndUserIdToMessages < ActiveRecord::Migration[5.2]
def change
add_column :messages, :body, :text
add_column :messages, :user_id, :integer
end
end

Rails InvalidForeignKey

I am developing a portfolio for my website, I decided to add skills to each portfolio item.
class PortfolioSkill < ApplicationRecord
belongs_to :portfolio
belongs_to :skill
end
class Portfolio < ApplicationRecord
has_many :portfolio_skills
has_many :skills, through: :portfolio_skills
def all_tags=(names)
self.skills = names.split(",").map do |name|
Skill.where(name: name.strip).first_or_create!
end
end
def all_tags
self.skills.map(&:name).join(", ")
end
def remove_skill_tags
PortfolioSkill.where(portfolio_id: id).destroy_all
end
end
create_table "portfolio_skills", force: :cascade do |t|
t.integer "portfolio_id"
t.integer "skill_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["portfolio_id"], name: "index_portfolio_skills_on_portfolio_id"
t.index ["skill_id"], name: "index_portfolio_skills_on_skill_id"
end
create_table "portfolios", force: :cascade do |t|
t.string "name"
t.string "client"
t.date "completed"
t.text "about"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "long_landscape"
t.string "cover"
t.integer "category_id"
t.index ["category_id"], name: "index_portfolios_on_category_id"
end
When I click destroy on the index page I get the
SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "portfolios" WHERE "portfolios"."id" = ?
error. All the associations look right. I used this same pattern for my tags on other models and it worked with no issues. Any help would be great.
You are deleting from portfolios table, but table portfolio_skills has a column referencing it as foreign key. Hence the error.
Trying to delete a parent without checking and deleting its associated children can lead to data inconsistency. This exception is in place to prevent that.
Rails dependent destroy will take care of removing associated children rows while removing a parent.
Try using a dependent destroy:-
class Portfolio < ApplicationRecord
has_many :portfolio_skills, :dependent => :destroy
...
end

Specify which foreign key table will be referred to inside of a migration

I'm developing my Ruby On Rails application that is using PostgreSQL as a database and I've faced a problem.
Here is my Questions table (schema.rb):
create_table "questions", primary_key: "hashid", force: :cascade do |t|
t.string "title"
t.text "body"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "questions", ["hashid"], name: "index_questions_on_hashid", unique: true, using: :btree
where hashid field (string) is being used instead of a default numeric id field.
Here's my migration for both Questions and Comments tables:
# Questions migration
class CreateQuestions < ActiveRecord::Migration
def change
create_table :questions, id: false do |t|
t.text :hashid, primary_key: true
t.string :title
t.text :body
t.timestamps null: false
end
add_index :questions, :hashid, unique: true
end
end
# Comments migration
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :body
t.references :question, foreign_key: :hashid
t.timestamps null: false
end
end
end
I want to relate Comments with Questions in my application using belongs_to and has_many relationship accordingly, but the default t.references :question is trying to relate by using id column from the target table.
Here is the migration error message:
== 20160326185658 CreateComments: migrating ===================================
-- create_table(:comments)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedColumn: ERROR: column "id" referenced in foreign key constraint does not exist
: ALTER TABLE "comments" ADD CONSTRAINT "comments_question_id_fk" FOREIGN KEY ("question_id") REFERENCES "questions"(id)
How could I relate by using other than id field? In my case it is hashid?
I would prefer to still name the primary key column id even when the column contains a random generated string.
To create a string id column in your database, use a migration like this:
create_table :questions, id: false do |t|
# primary key should not be nil, limit to improve index speed
t.string :id, limit: 36, primary: true, null: false
# other columns ...
end
In your model, ensure that a id is created:
class Question < ActiveRecord::Base
before_validation :generate_id
private
def generate_id
SecureRandom:uuid
end
end
When you are already in Rails 5 you might just want to use has_secure_token :id instead of the before_validation call back and the generate_id method.

rails_admin using outdated table names

I have two models connected with a has_and_belongs_to_many association: courses and semesters. rails_admin was only giving me the option to add semesters when creating a course, and not the other way around (and really, it's much more useful to add courses when creating a semester). I made some tweaks the migration:
def change
create_table "courses", force: :cascade do |t|
t.string "department"
t.integer "number"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "semesters", force: :cascade do |t|
t.integer "year"
t.string "season"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "semesters_courses", id: false, force: :cascade do |t|
t.integer "semester_id"
t.integer "course_id"
end
add_index "semesters_courses", ["course_id"], name: "index_semesters_courses_on_course_id"
add_index "semesters_courses", ["semester_id"], name: "index_semesters_courses_on_semester_id"
end
I renamed the intermediary table to semesters_courses from courses_semesters, just for clarity. Not only did this not solve the problem, but now when I try to add a new course, it 500s and tells me:
Could not find table 'courses_semesters'
I know I could make this go away by changing the name back, but I'm not sure where railsadmin is getting that name from (and suspect this to be the source of my problem). I've removed and reinstalled railsadmin, dropped and rewritten the tables, and cleared my browser's cache. When I search my entire project tree for "courses_semesters," I only get results in my error log.
New at Rails dev, so I assume I'm missing some config file somewhere that I need to update, but would love some help on where to find it.
You’re overwriting the join table name.
Option 1 you MUST specify the name of the join table in your models
app/models/course.rb
has_and_belongs_to_many :semesters, join_table: "semesters_courses"
app/models/semester.rb
has_and_belongs_to_many :courses, join_table: "semesters_courses"
Or Option 2 just rename your join table to "courses_semesters" by using migration.
rails g migration rename_courses_semesters
class RenameCoursesSemesters < ActiveRecord::Migration
def self.up
rename_table :semesters_courses, :courses_semesters
end
def self.down
rename_table :courses_semesters, :semesters_courses
end
end
Hope this answers your question.

Resources