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.
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. (ex: 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. I can iterate over @matched_keyskill.each do |k| k.job.company end
and get the company records. But, when I tried this method it results in n+1 query also the company name is getting repeated.
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.
You can use "joins" and "inclue" to remove the n+1 query:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.