Rails5 - Adding Foreign Keys to Existing Models in postgres - ruby-on-rails

I have two models. An Events model and an EventOption. The Events will have_many :event_options.
My issue is that when I try to do a migration to add_foreign key :event_options, :events so that I can link them up, I get the following error:
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column "event_id" referenced in foreign key constraint does not exist
: ALTER TABLE "event_options" ADD CONSTRAINT "fk_rails_3995702fad"
FOREIGN KEY ("event_id")
REFERENCES "events" ("id")
Here's my schema.rb:
ActiveRecord::Schema.define(version: 20160806001743) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "event_options", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.float "price"
t.text "description"
t.string "name"
end
create_table "events", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
t.boolean "active", default: true
end
create_table "users", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "email", null: false
t.string "encrypted_password", limit: 128, null: false
t.string "confirmation_token", limit: 128
t.string "remember_token", limit: 128, null: false
t.index ["email"], name: "index_users_on_email", using: :btree
t.index ["remember_token"], name: "index_users_on_remember_token", using: :btree
end
end
I know there are :id columns that work because I can play with them in the console. I know I'm missing something here to get the Foreign Keys working for the app, but for the life of me, I don't know what.

Wait, you mean the foreign key option for the has_many, that isn't what add_foreign_key does confusingly. It adds a foreign key constraint.
So in your migration you need to do add_column or add_reference first
add_reference :event_options, :event, index: true
add_foreign_key :event_options, :events

Related

Rails 7 - Undo/Remove a Schema.rb add_foreign_key reference & start over

I have started my project with a Users table and have since migrated to using an Accounts table. In the process I have an old reference to the Users table still in my schema.rb file and I need to remove it and create a new reference, or update the reference.
I am trying to work out a migration that will allow me to do this, however it keeps throwing an error as there's no Users table and when it did exist, it never had an account_id , which you can see referenced in my schema.rb file.
I really just need my schema.rb file to update
"add_foreign_key "likes", "users", column: "account_id"
to
add_foreign_key "likes", "accounts", column: "account_id"
But am finding this impossible to do with a migration without generating an error.
Any suggestions?
ActiveRecord::Schema.define(version: 2022_01_18_013836) do
create_table "accounts", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at", precision: 6
t.datetime "remember_created_at", precision: 6
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "username"
t.string "first_name"
t.string "last_name"
t.index ["email"], name: "index_accounts_on_email", unique: true
t.index ["reset_password_token"], name: "index_accounts_on_reset_password_token", unique: true
end
create_table "likes", force: :cascade do |t|
t.integer "account_id", null: false
t.integer "product_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["account_id"], name: "index_likes_on_account_id"
t.index ["product_id"], name: "index_likes_on_product_id"
end
create_table "products", force: :cascade do |t|
t.string "product_name"
t.string "product_category"
t.string "product_type"
t.string "product_image"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.text "product_description"
t.string "product_country"
end
add_foreign_key "likes", "products"
add_foreign_key "likes", "users", column: "account_id"
end
Best way to resolve this is to create a migration that adds users back with only account_id then remove the foreign key, and drop the user table again.
Should be doable in 1 migration, however I went about it as follows.
I ended up creating a new Users table with just an account_id:integer
Created a migration to remove_foreign_key
Then created a migration to then drop that Users table again.
Schema file is looking correct now and I have all the migrations to trace my changes.

Rails compound key to enforce uniqueness on the pair of values

I am trying to build a toy application and ran across an issue I cannot seem to solve. How do I enforce that a pair of values are unique in a table?
suppose the following schema:
create_table "courses", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "number"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "status", default: 0
end
create_table "professors", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "status", default: 0
end
create_table "sections", force: :cascade do |t|
t.integer "number"
t.integer "max_enrollment"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "professor_id"
t.integer "course_id"
t.string "room"
t.index ["course_id"], name: "index_sections_on_course_id"
t.index ["professor_id"], name: "index_sections_on_professor_id"
end
and I wanted to create a uniqueness constraint in the sections table that the professor_id paired with course_id must be unique. the only thing I have found in my digging is that you can use the validates keyword in the model to enforce the uniqueness of a single field... I also saw that there is a validates_with keyword but I cannot find any way of writing a validator to do what I'm looking for. any help would be greatly appreciated.
Add a unique constraint in your database (Pun in a migration):
add_index :sections, [:professor_id, :course_id], unique: true
Now also put a validation constraint in your Section model:
validates_uniqueness_of :professor_id, scope: :course_id
Now your professor_id will be uniquely validated in the scope of course_id. Also there will be a unique constraint in your database table.

Trying to change a column to "null: true" is not being reflected in schema after migration

I have a column/foreign key, resolver_id, that I want to be able to have null values (ie: Rails Migration to make a column null => true). Let's say I have the following line in my migration:
def
change_column_null :bugs, :resolver_id, true
end
However, after running a successful migration (ie, generate the migration and run rails db:migrate), the schema remains unchanged, besides the version number:
t.integer "resolver_id"
whereas I am expecting:
t.integer "resolver_id" , null: true
Is there something I'm missing?
I've also tried using just change_column like so:
change_column :bugs, :resolver_id, :integer, null: true
However, this is still not reflected in the schema. The rails g migration and db:migrate work just fine, and the version number in the schema matches the latest migration.
For reference, here is my schema:
ActiveRecord::Schema.define(version: 20170502203934) do
create_table "bugs", force: :cascade do |t|
t.string "name"
t.text "error_msg"
t.text "description"
t.text "causes"
t.boolean "resolved"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "resolver_id"
t.index ["resolver_id"], name: "index_bugs_on_resolver_id"
t.index ["user_id"], name: "index_bugs_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "first_name"
t.string "last_name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["username"], name: "index_users_on_username", unique: true
end
end
If relevant, the resolver_id foreign key is a reference a User model, ie:
class Bug < ApplicationRecord
# Associations
belongs_to :user
belongs_to :resolver, class_name: 'User'
end
null: true is the default behavior. You will never see it in your schema, you will see either null: false or nothing.

rails eager loading for one-to-many association

I have
class Article < ActiveRecord::Base
has_one :template
end
and
class Template < ActiveRecord::Base
has_many :articles
end
where Template model has got a room property. Now i'd like to build a list of all articles, where the articles template has a certain room value (say "bath").
I thought this is done by eager loading (resp: includes), but if i try
Article.includes(:template)
I get the error
SELECT "templates".* FROM "templates" WHERE "templates"."article_id" IN ('51', '52', '53', '54')
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column templates.article_id does not exist
LINE 1: SELECT "templates".* FROM "templates" WHERE "templates"."art...
What am I doing wrong?
EDIT
here's my schema.rb as asked
# encoding: UTF-8
# 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: 20160913122551) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "articles", force: :cascade do |t|
t.string "title"
t.text "details"
t.integer "value_eur"
t.integer "deposit_eur"
t.integer "location_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "picture"
t.float "rate_eur"
t.string "rate_interval"
t.integer "template_id"
t.integer "quality"
end
add_index "articles", ["location_id"], name: "index_articles_on_location_id", using: :btree
add_index "articles", ["template_id"], name: "index_articles_on_template_id", using: :btree
add_index "articles", ["user_id"], name: "index_articles_on_user_id", using: :btree
create_table "locations", force: :cascade do |t|
t.string "street_and_no"
t.string "postcode"
t.string "city"
t.string "country"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.float "latitude"
t.float "longitude"
end
add_index "locations", ["user_id"], name: "index_locations_on_user_id", using: :btree
create_table "templates", force: :cascade do |t|
t.string "title"
t.text "details_hint"
t.float "rate_eur"
t.string "rate_interval"
t.string "picture"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "room"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "role"
t.string "nickname"
t.string "firstname"
t.string "lastname"
t.string "phoneno"
t.boolean "showemail"
t.boolean "showphone"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["nickname"], name: "index_users_on_nickname", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
add_foreign_key "articles", "locations"
add_foreign_key "articles", "templates"
add_foreign_key "articles", "users"
add_foreign_key "locations", "users"
end
Your templates table does not have an article_id column according to the schema.rb you posted so you will need to create that reference.
Change
has_one :template
in the articles model to
belongs_to :template

RoR: Cannot Migrate Database to Heroku

I am having trouble migrating my database to Heroku. I have checked the other issues that address this to no avail. I can really use a second pair of eyes on my code to help me figure this out.
This is the error I get:
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
PG::UndefinedTable: ERROR: relation "props" does not exist
: ALTER TABLE "comments" ADD CONSTRAINT "fk_rails_1d3f70cf04"
FOREIGN KEY ("prop_id")
REFERENCES "props" ("id")
It seems to get caught while migrating this file:
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :commenter
t.text :body
t.references :prop, index: true, foreign_key: true
t.timestamps null: false
end
end
end
This is the migration file where I create the table props:
class CreateProps < ActiveRecord::Migration
def change
create_table :props do |t|
t.string :title
t.text :text
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
end
end
My schema is here:
ActiveRecord::Schema.define(version: 20160528205746) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "answers", force: :cascade do |t|
t.string "choice"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "created_by"
t.integer "user_id"
t.integer "prop_id"
end
create_table "comments", force: :cascade do |t|
t.string "commenter"
t.text "body"
t.integer "prop_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "comments", ["prop_id"], name: "index_comments_on_prop_id", using: :btree
create_table "props", force: :cascade do |t|
t.string "title"
t.text "text"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "choice"
t.string "answer"
t.integer "answerId"
end
add_index "props", ["user_id"], name: "index_props_on_user_id", using: :btree
create_table "user_answers", force: :cascade do |t|
t.integer "user_id"
t.integer "answer_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "email"
t.integer "score", default: 0
t.integer "prop_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.string "created_by"
t.boolean "admin", default: false
t.integer "answers_id"
t.integer "answer_id"
end
add_index "users", ["answer_id"], name: "index_users_on_answer_id", using: :btree
add_index "users", ["prop_id"], name: "index_users_on_prop_id", using: :btree
create_table "wins", force: :cascade do |t|
t.string "correctAnswer"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "wins", ["user_id"], name: "index_wins_on_user_id", using: :btree
add_foreign_key "users", "answers"
end
The problem is you are creating a reference to a table that is not yet created. Remove the reference from that migration to props, then add the props table and then add a migration implementing the association. If you dont need the data currently in the db I would do a "rake db:drop" and edit the migration files (only if you arent collaborating with others!)
Update:
Do rails g migration add_ref_to_comments
Then edit the migration to have:
def change
add_reference :props, :comment, index: true
end

Resources