我有以下模型:项目,开发人员和主题。我还有一些连接表:ProjectTopic和DeveloperTopic。
我希望能够找到与项目的给定实例具有相同主题的所有开发人员。我可以通过执行Project.first.topics来获取项目的主题,但我不能使用topic列进行Developer.where查询,因为它不存在 - 它只是通过连接表/通过关联创建的方法。 / p>
如何找到与给定项目具有相同主题的所有开发人员?
class Developer < ActiveRecord::Base
has_many :projects
has_many :developer_technologies
has_many :technologies, through: :developer_technologies
has_many :developer_topics
has_many :topics, through: :developer_topics
end
class Project < ActiveRecord::Base
has_many :technologies, through: :project_technologies
has_many :topics, through: :project_topics
has_many :project_technologies
has_many :project_topics
belongs_to :customer
belongs_to :developer
end
class ProjectTopic < ActiveRecord::Base
belongs_to :project
belongs_to :topic
end
class Topic < ActiveRecord::Base
has_many :developers
has_many :developer_technologies, through: :developers
has_many :projects
has_many :project_technologies, through: :project
end
class DeveloperTopic < ActiveRecord::Base
belongs_to :developer
belongs_to :topic
end
答案 0 :(得分:0)
对此不太确定,但值得一试:
class Developer < ActiveRecord::Base
def find_whatever(project)
includes(:topic).where("topics.project_id" => project.topics_ids)
end
您需要将topics_ids委托给项目。
答案 1 :(得分:0)
如果一个项目有主题[A,B,C],并且开发人员有主题[C,D,E],那么这是否算作您正在寻找的内容,因为它们都共享主题C?或者你的意思是开发者必须完全具有[A,B,C]和其他一些主题吗?
如果您想要第一个案例,那么我认为您应该能够通过首先执行Project.first.topics.includes(:developers)来获得与每个主题相关联的开发人员。然后是一些如何将开发人员合并到一个列表中。
请注意,在您的主题模型中,您可能应该通过DeveloperTopic连接表连接到developers表,而不是直接连接到开发人员表。
答案 2 :(得分:0)
通过遍历所有开发人员并在每个开发人员上调用.topics,然后根据项目的主题进行检查,以及是否匹配,将开发人员推送到数组中来实现此目的。