【发布时间】:2017-10-25 23:26:14
【问题描述】:
我正在尝试在我的 Rails 应用程序中实现基本的记录过滤。但我在使用belongs_to 和has_many 关联进行过滤时遇到问题。
我有 3 个模型:Job、JobCategory、Tag。标签是通过acts_as_taggable_on gem 实现的。
我的Job 模型中有一些范围,看起来可以正常工作:
class Job < ApplicationRecord
belongs_to :job_category
acts_as_taggable_on :tags
scope :join_tags, -> { includes(:tags) }
scope :salary_min, lambda { |salary_min|
where('salary_min >= ? or salary_min IS NULL', salary_min)
.where('salary_max >= ? or salary_max IS NULL', salary_min)
.where('salary_min >= ? or salary_min IS NULL', salary_min)
}
scope :salary_max, lambda { |salary_max|
where('salary_min <= ? or salary_min IS NULL', salary_max)
.where('salary_max <= ? or salary_max IS NULL', salary_max)
}
scope :by_category, lambda { |*category_id|
includes(:job_categories).where(job_category_id: category_id)
}
scope :tagged_with_id, lambda { |*tag_id|
joins(:taggings).where(taggings: { tag_id: tag_id })
}
end
我在JobsController 中的索引操作是:
def index
if params[:tag]
@jobs = Job.tagged_with(params[:tag])
.filter(params.slice(:salary_min, :salary_max, :by_category, :tagged_with_id))
else
@jobs = Job.published.filter(params.slice(:salary_min, :salary_max, :by_category, :tagged_with_id))
.join_tags
end
@job_categories = JobCategory.all
end
我可以从视图中调用 2 个作用域:
= form_for jobs_path, method: 'get' do |f|
= f.label 'Salary from'
= text_field_tag :salary_min, params[:salary_min]
= f.label 'Salary to'
= text_field_tag :salary_max, params[:salary_max]
= f.submit 'Filter', name: nil
如何调用其他范围来按多个类别和标签过滤记录?
我需要调用by_category 和tagged_with_id 范围,但不明白我该如何正确地做到这一点。
在我的应用程序的其他表单中,我使用接下来的 2 个表单助手:
= f.collection_check_boxes :job_category_ids, JobCategory.order('priority DESC'), :id, :title, hide_label: true
= f.collection_select :tag_list, ActsAsTaggableOn::Tag.all.order(:name), :name, :name, {hide_label: true}, html_options = {class: 'js-example-basic-multiple', multiple: 'multiple'}
我想使用这些帮助程序,但如果可能的话,将过滤器参数传递给控制器。
【问题讨论】:
标签: ruby-on-rails activerecord filtering acts-as-taggable-on