cjm2671
cjm2671

Reputation: 19456

How can I relate to an object twice in rails?

I've got a Users model and a Tasks model.

A task has a creator, of type user, and an assignee of type user.

I've already done a migration of AddUserIdtoTasks to get the creator relation working, but now I need to do the same thing again to add the assignee, but I'm already using the keyword 'user'. How should I go about building a proper relation.

A task only has one assignee, always.

I'm using devise for the user model.

Upvotes: 1

Views: 215

Answers (2)

Fabio
Fabio

Reputation: 19176

Create the field assignee_id in your Task model and then use it for the relation as in

class Task < AR::Base
  belongs_to :assignee, :class_name => 'User'
end

On the other side of the relation

class User < AR::Base
  has_many: :assigned_tasks, :class_name => 'Task', :foreign_key => :assignee_id
end

Sorry, should be :class_name. Updated User class also with a :foreign_key parameter, without it user.assigned_tasks would have joined records using the :user_id parameter (the default value for has_many, i.e. "#{class_name}_id"`).

I invite you to read the link I've posted, it explains better than me all these things.

Source: http://guides.rubyonrails.org/association_basics.html#detailed-association-reference

Upvotes: 0

Evan Cordell
Evan Cordell

Reputation: 4118

has_one :creator, :class_name => "User"
has_one :asignee, :class_name => "User"

Or belongs_to, depending on how your fields are set up. has_one and belongs_to both take an optional :class_name argument for cases just such as yours.

Upvotes: 2

Related Questions