eudaimonia
eudaimonia

Reputation: 1536

Rename field in relation added to existing model

I want to add relation that user can belongs_to teacher. Teachers are stored in Admins table. Typically it will be nobody (nil), but for active students, I would add a specific person who is their teacher at the moment.

Normally I think could do run such migration:

class AddTeacherToUser < ActiveRecord::Migration
  def change
    add_reference :users, :admin, index: true
  end
end

Then in models, I could add like that:

class User < ApplicationRecord
  belongs_to :admin
 ...

class Admin < ApplicationRecord
  has_many :users
...

But I want to have on my user field teacher_id, not admin_id is this possible? can I rename a field in migration or inside my model? Rails version: 4.2

Upvotes: 0

Views: 138

Answers (1)

John Baker
John Baker

Reputation: 2398

In Rails 4.2+ you can set foreign keys in the db:

In your migration do:

add_reference :users, :teacher, index: true
add_foreign_key :users, :admins, column: :teacher_id

While in your User model do:

belongs_to :teacher, class_name: "Admin"

Upvotes: 4

Related Questions