When one table has 2 columns which refer same master table with ActiveRecord on Rails3
There are tables like below.
Depts
id
dept_name
Users
id
dept_id
previous_dept_id
Users table has two columns which refer Depts table.
How can I get dept_name for each columns?
class Dept < ActiveRecord::Base
has_many :user
end
class User < ActiveRecord::Base
belongs_to :dept
end
I think what you’re looking for is the following:
You should then be able to access the two departments like this:
It’s important to note that your
Deptmodel will only find users by thedept_idcolumn. I think you’d have to add a secondhas_manytoDeptif you needed to find users by their previous dept. Something like: