What is the class of an association based on the foreign key attribute only?

Viewed 4375

Short: I have an foreign key attribute and want to know what is the class (or reference table) of that foreign key field.

Context:

given 2 tables: users(id, [other fields]) and issues(id, user_id, assigned_to, [other fields])

Here is my active record of Issue (irrelevant parts are extracted)

class User < ActiveRecord::Base
  ...
end
class Issue < ActiveRecord::Base
  belongs_to :user
  belongs_to :assigned_user, :foreign_key => 'assigned_to', :class_name => 'User'
  ...
end

I want to make a user readable change logging. e.g. when changing assigned user I want to get a message like this: Assigned to is changed from Otto to Zoltan. ActiveRecord has the function changes which is a good starting point but it give me only reference ID-s. To translate into names I need to read user by id.

For association :user it is quite easy because I have to follow conventions only. But how to fetch the same info for assigned_to attribute (I want to make a general solution)? Is it possible to figure out whether we have association for the given attribute? Can we extract the class of that association?

2 Answers
Related