ActiveRecord foreign keys

Hi all,

I have a small problem with ActiveRecord and I was wondering if anyone can help me.
I have 2 tables: users and activities and inside activities I have a foreign key (user_id) to the user table. Everything is ok.

I want now to add another foreign key to users, called added_by_user_id. I’ve changed the model to Activity:
belongs_to :user, :foreign_key => ‘user_id’
belongs_to :user, :foreign_key => ‘added_by_user_id’

but now activity.user is not defined anymore.

I was wondering if there is any way to ‘map’ the users in different attributes of activity. I’ve checked the API but couldn’t find anything.

Any help is much appreciated.


Hi Paul

belongs_to :user, :foreign_key => ‘user_id’
belongs_to :user, :foreign_key => ‘added_by_user_id’

the first parameter (:user) has to be different for the second user reference otherwise it conflicts with the first declaration (you can use something like “user_who_added_it” - but you’ll want to find a better name :slight_smile:

this should work:

belongs_to :user
belongs_to :added_by_user, :class_name => ‘User’, :foreign_key => ‘added_by_user_id’

Then you’ll have access to the use who added through mymodel.added_by_user