Two belongs_to refering the same model ?

Hi,

My task manager has a task model:

class Task < ActiveRecord::Base
  belongs_to :project
  belongs_to :user # responsible of the task
end

By adding belongs_to :user, my task objets have a user method:
name = Task.find(1).user.name

I'd like to add a creator (or created_by) method pointing to the user
table.
How can I do that ?

Something like belongs_to :user, :name=>'creator' # creator of the task,
refering to creator_id in the Task table.

Thanks for your pointers,
Mickael.

Hi,
I would create to foreign keys for tasks, maintainer_id and
creator_id, and then set up the model as follows:
class Task < ActiveRecord::Base
  belongs_to :maintainer, :class_name => "User"
  belongs_to :creator, :class_name => "User"
end

You can see the documentation for belongs_to here:
http://www.railsdocumentation.org/api/classes/ActiveRecord/Associations/ClassMethods.html#M000761

I hope this helped you.

Greetings
Christoph

Thanks Christoph! That's exactly what I needed:
belongs_to creator, :class_name => "user", :foreign_key => "creator_id",

Christoph wrote:

Thanks Christoph! That's exactly what I needed:
belongs_to creator, :class_name => "user", :foreign_key => "creator_id",

from rails 2 (possibly earlier; not quite sure) the :foreign key
option isn't needed in cases like this (it defaults to
association_name_id)

Fred

xiexie Fred,

In the real app code my column is named "created_by", so if I want a
"creator" I need a :foreign_key => "created_by" (just for info on the
real problem, thanks again for the info)

Mickael.

Frederick Cheung wrote: