ActiveRecord foreign keys

Hi all,

I have a small problem with ActiveRecord and I was wondering if anyone
help me.
I have 2 tables: users and activities and inside activities I have a
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

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

this should work:

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

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




This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs