Multiple associations to the same class


#1

Hi,

I cannot seem to create associations like this:

class Project < ActiveRecord::Base
belongs_to :manager, :class_name => ‘User’, :foreign_key => ‘manager’
belongs_to :liaison, :class_name => ‘User’, :foreign_key => ‘liaison’
end

p = Project.new
p.manager
=> 1

trying to retrieve associated objects doesn’t work and I only receive
the
associated record’s ID value as a Fixnum instance. Is there any way to
implement this particular association?


#2

I guess you should name you association different to the table’s field
name.

Kent.


#3

sorry I mispasted my User class:

class User < ActiveRecord::Base

has_many :bugs_opened, :class_name => “Bug”, :foreign_key => “opened_by”

has_many :bugs_assigned, :class_name => “Bug”, :foreign_key =>
“assigned_to”


#4

On 2/14/06, Kent S. removed_email_address@domain.invalid wrote:

I guess you should name you association different to the table’s field name.

Exactly right, that’s how I got this sort of setup running. You should
try

belongs_to :manager_user, :class_name => ‘User’, :foreign_key =>
‘manager’
belongs_to :liaison_user, :class_name => ‘User’, :foreign_key =>
‘liaison’

or somesuch. Then call project.manager_user when you want the user.

Either that or rename your “manager” column to “manager_id” in the db.

In my class it’s like:

class Bug < ActiveRecord::Base

belongs_to :opened_by_user, :class_name => “User”, :foreign_key =>
“opened_by”

belongs_to :assigned_to_user, :class_name => “User”, :foreign_key =>
“assigned_to”

end

class Bug < ActiveRecord::Base

belongs_to :opened_by_user, :class_name => “User”, :foreign_key =>
“opened_by”

belongs_to :assigned_to_user, :class_name => “User”, :foreign_key =>
“assigned_to”

end


#5

hmm, I got it to work by appending ‘_id’ to the :foreign_key values,
like
so: ‘manager_id’


#6

I imagine you don’t then need :foreign_key => ‘manager_id’ I bet RoR
will make that association for you

_T

I wish; it took my hours to find you NEED to define foreign_key if you
use class_name


#7

Douglas T. wrote:

hmm, I got it to work by appending ‘_id’ to the :foreign_key values,
like
so: ‘manager_id’

I imagine you don’t then need :foreign_key => ‘manager_id’ I bet RoR
will make that association for you

_T