代码之家  ›  专栏  ›  技术社区  ›  Marat Tynarbekov

rails 5通过has_many搜索

  •  1
  • Marat Tynarbekov  · 技术社区  · 8 年前

    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
    

    我想创建一个搜索,找到所有的项目,包括一套技能。

    例如:

    • 项目2技能:ruby、c++。

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

    3 回复  |  直到 8 年前
        1
  •  2
  •   Robin Daugherty    8 年前
    Project.joins(:skills).where(skills: { name: "c++" })
    

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

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

        2
  •  1
  •   moveson Andrey Deineko    8 年前

    我会使用 includes 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关系。

        3
  •  0
  •   Pramod Solanky    8 年前

    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公司