简体   繁体   中英

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

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

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 (ie not need to manually specify a foreign_key ), then you could call the database column creator_id instead of created_by .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM