【问题标题】:has_many of the same table through several othershas_many 同一张表通过其他几个
【发布时间】:2014-11-28 12:23:12
【问题描述】:

我想做的是: 我有一个用户模型,我有一个任务模型 任务有两种类型的用户 Owners 和 Supervisors 都是用户!

所以我到目前为止是:

任务模型

class Task < ActiveRecord::Base
  has_many :task_owners, dependent: :destroy
  has_many :task_supervisors, dependent: :destroy
  has_many :users, through: :task_owners
  has_many :users, through: :task_supervisors
end

TaskSupervisor 模型

class TaskSupervisor < ActiveRecord::Base
  belongs_to :task
  belongs_to :user
end

TaskOwner 模型

class TaskOwner < ActiveRecord::Base
  belongs_to :task
  belongs_to :user
end

最后是用户模型

class User < ActiveRecord::Base
  has_many :task_owners
  has_many :task_supervisors
  has_many :tasks, through: :task_owners
  has_many :tasks, through: :task_supervisors
end

现在你可以想象......我的问题是当我得到一个任务并检索用户时,我只得到我的一个关联......我需要的是一种更改吸气剂名称或识别它们的基本方法能够说类似的话

task.owners
task.supervisors

【问题讨论】:

  • 你为什么有这个两次? has_many :users, through: :task_ownersUser 模型也应该有:has_many :tasks(任务的复数)
  • @TheChamp 对不起......复制粘贴问题......我马上清理它
  • 至于 has_many 任务,这是一个真正的错误 :)
  • 您能否再描述一下这个问题?我不明白您所说的“您只检索一个关联”是什么意思。当您致电task.task_owners 时,这不是预期的吗?

标签: ruby-on-rails ruby associations model-associations


【解决方案1】:
class Task < ActiveRecord::Base
  has_many :task_owners, dependent: :destroy
  has_many :task_supervisors, dependent: :destroy
  has_many :owners, through: :task_owners, source: :users
  has_many :supervisors, through: :task_supervisors, source: :users
end

你应该能够做到这一点。

那么你应该得到你的task.ownerstask.supervisors

编辑:

您需要将用户模型更改为

class User < ActiveRecord::Base
  has_many :task_owners
  has_many :task_supervisors
  has_many :owned_tasks, through: :task_owners, source: :tasks
  has_many :supervised_tasks, through: :task_supervisors, source: :tasks
end

【讨论】:

  • + 1 个喜欢这个。 ;) 小错字:to 而不是 too
  • 我在实施您的解决方案时得到了这个......但我认为这是我一直在寻找的东西 ActiveRecord::HasManyThroughSourceAssociationNotFoundError: 找不到源关联:owner 或 :owners in模型任务所有者。试试 'has_many :owners, :through => :task_owners, :source => '。它是 :task 还是 :user 之一?
  • 我会用谷歌搜索...如果我能解决它,我一定会选择你的答案作为“那个”
  • @KarimMagdyMansour 已更新,只需标记源代码即可。由于指定了来源,不确定是否需要class_name,我怀疑不是。
  • 我会删除那个位
猜你喜欢
  • 1970-01-01
  • 2014-11-28
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 2014-08-10
  • 1970-01-01
  • 2012-11-16
  • 1970-01-01
相关资源
最近更新 更多