Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After renaming a model and changing all references to the model, a reference remains to the previous name

I had a model called Person after following a tutorial online. After a while we decided that it was more sensible to rename it to User. I went through the code base and did the following:

  1. Renamed all instances of Person to User, person to user, People to Users and people to users, taking care not to clobber anything unrelated.
  2. Renamed all model files appropriately.

I have another model called session:

session belongs_to user

and

user has_many sessions

Prior to running migrations git grep -i person / people and find | grep person / people just return migrations so I'm sure that I have renamed everything properly.

When I go to create a new user which subsequently creates a session I get the following error:

unknown attribute: user_id

Running git grep again I find that the foreign key in sessions is still person_id

create_table "sessions", :force => true do |t|                                                                                                                             
    t.integer  "person_id
    t.string   "ip_address"                                                                                
    t.string   "path"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
end    

How can I fix this?

like image 465
Jonathan Evans Avatar asked Oct 04 '12 10:10

Jonathan Evans


2 Answers

just do in a migration

def change
   rename_column :sessions, :person_id, :user_id
end
like image 102
Aayush Khandelwal Avatar answered Oct 16 '22 15:10

Aayush Khandelwal


If you change the name of an association, but not the name of the underlying column, you have to make it explicit in the association:

class Session 
  belongs_to :user, :foreign_key => "person_id", :inverse_of => :sessions
end

class User
  has_many :sessions, :foreing_key => "person_id", :inverse_of => :user
end
like image 1
rewritten Avatar answered Oct 16 '22 15:10

rewritten