Yshmarov
Yshmarov

Reputation: 3749

rails belongs_to same model twice

I have a Task model (fields = description, soldier_id:integer, created_by:integer).

Now I automatically assign created_by to the soldier that creates a task, and I want to use the soldier_id for the soldier that must execute the task. This way, Task belongs to Solider in 2 different fields at the same time. How should it be done properly? Now I have:

class Task < ActiveRecord::Base
  belongs_to :soldier
end 

and

class Soldier < ActiveRecord::Base
  has_many :tasks
end

Upvotes: 2

Views: 1198

Answers (2)

Tom Lord
Tom Lord

Reputation: 28305

Something like this:

class Task < ActiveRecord::Base
  belongs_to :soldier
  belongs_to :creator, class_name: Soldier, foreign_key: :created_by
end

class Soldier < ActiveRecord::Base
  has_many :tasks

  # Optional -- I'm unclear if you want this too?
  has_many :created_tasks, class_name: Task, foreign_key: :created_by
end

The above implementation is OK. However, if you wish to stick within rails conventions (i.e. not need to manually specify a foreign_key), then you could call the database column creator_id instead of created_by.

Upvotes: 4

Ursus
Ursus

Reputation: 30071

Try this one

class Task < ActiveRecord::Base
  belongs_to :soldier
  belongs_to :creator, class_name: 'Soldier', foreign_key: :created_by
end 

Now, given a task object, you can use task.creator to retrieve the soldier you want

Upvotes: 2

Related Questions