操纵ActiveRecord关联关系

操纵ActiveRecord关联关系,activerecord,relationship,Activerecord,Relationship,我目前正在进行重构,将关系从一->多调整到多。出于各种原因,我们需要维持现有关系的一部分,这样我们才能维持现有合同 为了解决问题,让我们调用这些模型任务< /代码>和团队>代码>,并考虑额外的1个:团队>代码>和成员< /代码>之间的许多关系。鉴于以下情况: class Task < ApplicationRecord belongs_to :team has_one :captain, -> {//some join/ordering code}, through: :te

我目前正在进行重构,将关系从一->多调整到多。出于各种原因,我们需要维持现有关系的一部分,这样我们才能维持现有合同

为了解决问题,让我们调用这些模型<代码>任务< /代码>和<代码>团队>代码>,并考虑额外的1个:<代码>团队>代码>和<代码>成员< /代码>之间的许多关系。鉴于以下情况:

class Task < ApplicationRecord
  belongs_to :team
  has_one :captain, -> {//some join/ordering code}, through: :team, source: :members
end
class Task < ApplicationRecord
  has_many :tasks_teams
  has_many :teams, through: :tasks_steams

  has_one :head_team, -> (task) {joins(:tasks_teams).where(task_id: task.id)}, class_name: 'Team'

  has_one :captain, -> {//some join/ordering code}, through: :team, source: :members
end
目前,团队类型已被省略,但我当前的计划是添加一个布尔字段
tasks\u teams
,以指定一个团队满足在
团队
关系中被选择的要求,并且只允许一条记录将该值设置为
true

总结最终目标:

  • task.teams
    返回所有
    teams
    tasks\u teams
  • task.team
    通过
    tasks\u teams
    返回一个
    team
    ,它的单态布尔列的值为
    true
    (例如,您可以称之为,
    已调度
    ),但如果我们可以在
    team
    上取消现有的
    team\u type
    关系,那就更好了

非常感谢您的阅读,非常感谢您的帮助

我发现了一个涉及
unscope(:where)
的选项,但我不确定这是最好的方法。
class Task < ApplicationRecord
  has_many :tasks_teams
  has_many :teams, through: :task_teams
end
class TasksTeam < ApplicationRecord
  belongs_to :task
  belongs_to :team

  validates :task_id, presence: true
  validates :team_id, presence: true
end
class Team < ApplicationRecord
  has_many :tasks_teams
  has_many :tasks, through: :task_teams

  has_many :members
  belongs_to :team_type
end
class Task < ApplicationRecord
  has_many :tasks_teams
  has_many :teams, through: :tasks_steams

  has_one :head_team, -> (task) {joins(:tasks_teams).where(task_id: task.id)}, class_name: 'Team'

  has_one :captain, -> {//some join/ordering code}, through: :team, source: :members
end
ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR:  column teams.task_id does not exist)
LINE 1: ...teams"."task_id" = "teams"."id" WHERE "tea...
                                                             ^
: SELECT  "teams".* FROM "teams" INNER JOIN "tasks_teams" ON "tasks_teams"."team_id" = "teams"."id" WHERE "teams"."task_id" = $1 AND "tasks_teams"."task_id" = $2 LIMIT $3