我不知道我是如何描述这个问题的,起初我想展示我的模型,它维持下面的关系 category.rb class Category ApplicationRecord has_many :job_categories, dependent: :destroy has_many :jobs, through: :job_categoriesend job
category.rb
class Category < ApplicationRecord has_many :job_categories, dependent: :destroy has_many :jobs, through: :job_categories end
job.rb
class Job < ApplicationRecord has_many :job_categories, dependent: :destroy has_many :categories, through: :job_categories end
job_category.rb
class JobCategory < ApplicationRecord belongs_to :category, counter_cache: :jobs_count belongs_to :job end
schema.rb
create_table "categories", force: :cascade do |t| t.string "name" t.string "parent" end
parent是一个专栏,它维护着像Technology这样的组,并且在这个与技术相关的ruby,rails,编程等之下.
以下是我按类别显示的查询
Category.select(:id, :name, :parent).group_by{|p| p.parent}
它就像这样显示出来
技术
>ruby
>铁轨
>等
现在我想通过技术显示组中的所有作业,我对此有一个查询
Job.joins(:categories).where('lower(categories.parent) LIKE lower(?)', "%#{params[:parent]}%")
并且它显示错误的输出,就像我只有一个类别是ruby,rails然后这一个作业显示两次,一个用于ruby,一个用于rails.
谢谢
您的关联是正确的,您可以通过以下方式检索某些类别的所有唯一作业:Job.joins(:job_categories).joins(:categories).where('lower(categories.parent) LIKE lower(?)', "%#{params[:parent]}%").distinct
这将使用相关键上的中间表job_categories和作业连接作业,然后where子句将允许您选择要检索的内容.
SELECT DISTINCT "jobs" .* FROM "jobs" INNER JOIN "job_categories" ON "job_categories" ."job_id" = "jobs" ."id" INNER JOIN "job_categories" "job_categories_jobs_join" ON "job_categories_jobs_join" ."job_id" = "jobs" ."id" INNER JOIN "categories" ON "categories" ."id" = "job_categories_jobs_join" ."category_id" WHERE ( lower ( categories.parent ) LIKE lower ( "Technology" ) )
更新:
实际上,我们也不需要明确加入job_categories,以下内容就足够了:
Job.joins(:categories).where('lower(categories.parent) LIKE lower(?)', "%#{params[:parent]}%").distinct SELECT DISTINCT "jobs".* FROM "jobs" INNER JOIN "job_categories" ON "job_categories"."job_id" = "jobs"."id" INNER JOIN "categories" ON "categories"."id" = "job_categories"."category_id" WHERE (lower ( categories.parent ) LIKE lower ( "Technology" ))