Maayan Naveh
Maayan Naveh

Reputation: 370

Creating ActiveRecord Associations on Existing Columns

I have two models: User and Listing. I am trying to set up a one-to-many relationship between them via existing db columns.

class User < ApplicationRecord
  has_many :listings

class Listing < ApplicationRecord
   belongs_to :user, foreign_key: "user_id"

This is my migration:

class AddFkToListing < ActiveRecord::Migration[5.1]
  def change
    add_foreign_key :listings, :users, column: :user_id, primary_key: :user_id
  end
end

But it created the foreign key in table users on column id. Any idea how to do this properly?

Here is the DB schema:

  create_table "listings", force: :cascade do |t|
    t.integer "listing_id"
    t.string "state"
    t.integer "user_id"
    t.string "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["listing_id"], name: "index_listings_on_listing_id", unique: true
  end

  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.boolean "admin", default: false
    t.string "activation_digest"
    t.boolean "activated", default: false
    t.datetime "activated_at"
    t.string "reset_digest"
    t.datetime "reset_sent_at"
    t.string "request_token"
    t.string "request_secret"
    t.string "oauth_verifier"
    t.string "oauth_token"
    t.string "login_name"
    t.integer "user_id"
    t.index ["email"], name: "index_users_on_email", unique: true
  end

Thank you so much!

Upvotes: 1

Views: 43

Answers (1)

nattfodd
nattfodd

Reputation: 1890

Since you have a conventional foreign key field name (user_id in listings table), I believe this should work just fine for you:

class AddFkToListing < ActiveRecord::Migration[5.1]
  def change
    add_foreign_key :listings, :users
  end
end

The syntax of add_foreign_key is:

  • first argument (:listings) - table which should contain foreign key
  • second argument (:users) - table which should be used for constraint
  • column: :user_id - specifies to which field of the listings table constraint should be applied
  • primary_key: - specifies the field of the users table to build a constraint

(see https://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_foreign_key)

The primary_key: :user_id part in your example actually refers (tries to) to non-existing user_id field in users table.

Upvotes: 1

Related Questions