rails 5 搜索 has_many 通过

rails 5 search by has_many through

我有三个模型

class Project < ApplicationRecord
  has_many :project_skills
  has_many :skills, :through => :project_skills
end

class Skill < ApplicationRecord
  has_many :project_skills
  has_many :projects, :through => :project_skills
end

class ProjectSkill < ApplicationRecord
  belongs_to :skill
  belongs_to :project
end

我想创建一个搜索来查找包含一组技能的所有项目。

例如:

所以,当我搜索 "ruby" 时,我的结果应该是 project1 和 project2。

Project.joins(:skills).where(skills: { name: "c++" })

将 return 个具有 "c++" 技能的项目。

Project.joins(:skills).where(skills: { name: ["c++", "ruby"] })

将 return 个具有 "c++" 或 "ruby" 技能或两者的项目。

如果全文搜索是您的意思,我建议 solr 使用 sunspot 作为其 rails 客户端。您可以阅读更多关于太阳黑子的信息 here

如果另一方面,您需要的只是获取关联,那么这就是我要做的。

#considering params[:name] = 'ruby'  
# also considering you have a name field on skills table :) You can use the field you use to store skill name. 
skill = Skill.find_by_name(params[:name])
@projects = skill.projects 
# This is what you need to get projects corresponding a particular skill in a has many through association. 

但是对于非常复杂的全文搜索,我肯定会推荐solr

我会使用 includes 方法,它允许 ActiveRecord 自由确定连接表的最佳方式。此外,这看起来是一个很好的范围候选者。我假设技能是使用字段 name 命名的,但要替换为您实际使用的字段。

class Project < ApplicationRecord
  has_many :project_skills
  has_many :skills, :through => :project_skills

  scope :having_skill, -> (required_skill) { includes(:skills).where(skills: {name: required_skill}) }

end

现在您可以:

>> projects = Project.having_skill('ruby')

并取回包含结果集的 ActiveRecord 关系。