has_many关系之间的查询

时间:2014-04-22 22:10:13

标签: ruby-on-rails

我有一个项目模型,其中包含以下内容

has_many :project_topics
has_many :topics, :through => :project_topics

我需要一种方法来查询topic id并让它返回所有具有该主题的项目。有什么想法吗?

def projects_by_topic(topic)
end

1 个答案:

答案 0 :(得分:1)

我会尝试这样的事情。并查看Rails guild on ActiveRecord

def projects_by_topic(topic)
  project_topics = ProjectTopics.where(topic_id: topic.id)
  project_topics_ids = project_topics.map {|pt| pt.id }
  projects = Project.where(project_topic_id: project_topics_ids)
end