1

我有三个模型

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

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

例如:

  • project1 技能:java、ruby、html
  • project2 技能:ruby、c++。

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

4

3 回答 3

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

将返回具有“c++”技能的项目。

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

将返回具有“c++”或“ruby”技能或两者兼有的项目。

于 2017-07-23T17:21:39.550 回答
1

我会使用这种includes方法,它允许 ActiveRecord 自由地确定加入表格的最佳方式。此外,这看起来是一个很好的范围候选者。我假设技能是使用 field 命名的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 Relation。

于 2017-07-23T17:37:27.133 回答
0

如果全文搜索是您的意思,我建议solr使用sunspot它的 rails 客户端。您可以在此处阅读有关太阳黑子的更多信息。

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

#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

于 2017-07-23T17:30:23.490 回答