简体   繁体   English

Rails中的n + 1查询,需要解决方案

[英]n+1 query in rails, need solution

Below given are the model in my application. 下面给出的是我的应用程序中的模型。 I am trying to find all the companies that matches the keyskills. 我正在尝试找到所有与按键技术匹配的公司。 For example. 例如。 If I type java in my search-box it should get me all the companies that are matching and keyskills. 如果我在搜索框中键入java,它将使我获得所有匹配的公司和按键技能。

class User < ActiveRecord::Base
  has_one :company
end

class Company < ActiveRecord::Base
  has_many :jobs
  belongs_to :user
end

class Job < ActiveRecord::Base
  belongs_to :company
  has_many :key_skills, dependent: :destroy
  accepts_nested_attributes_for :key_skills, reject_if: :all_blank, allow_destroy: true
end

class KeySkill < ActiveRecord::Base
  belongs_to :job
end

The steps that I am following are, 我要遵循的步骤是

step1: Find all the keyskills matching the entered word. 步骤1:找到与输入单词匹配的所有按键技巧。 (ex: java) (例如:java)

@matched_keyskills = KeySkill.where('name like ?','java')

Since I have association between jobs and keyskills, that is jobs has_many key_skills and key_skills belongs_to job. 由于我在作业和按键技能之间存在关联,因此作业has_many key_skills和key_skills属于jobs。 I can iterate over @matched_keyskill.each do |k| 我可以遍历@ matched_keyskill.each | k | k.job.company end k.job.company结束

and get the company records. 并获取公司记录。 But, when I tried this method it results in n+1 query also the company name is getting repeated. 但是,当我尝试此方法时,它还会导致n + 1查询,并且公司名称也会重复出现。

Is there a way through which I can get only the company name shown on show page then by clicking on company it shows the jobs associate to it. 有没有一种方法可以让我只获得显示在显示页面上的公司名称,然后单击公司显示与之相关的职位。 also kindly let me know is the db model and association are correct inorder to achieve it. 也请让我知道db模型和关联是否正确才能实现它。

You can use "joins" and "inclue" to remove the n+1 query: 您可以使用“ joins”和“ inclue”删除n + 1个查询:

Try this, it will give you the list of all companies as You required. 尝试此操作,它将根据需要提供所有公司的列表。

Company.joins(key_skill: :job).where('key_skill.name like ?','java')

you can also use eager loading. 您还可以使用预先加载。

http://railscasts.com/episodes/22-eager-loading http://railscasts.com/episodes/22-eager-loading

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM