【问题标题】:Filtering search results in the views by associated records in Rails通过 Rails 中的关联记录过滤视图中的搜索结果
【发布时间】:2017-10-25 23:26:14
【问题描述】:

我正在尝试在我的 Rails 应用程序中实现基本的记录过滤。但我在使用belongs_tohas_many 关联进行过滤时遇到问题。

我有 3 个模型:JobJobCategoryTag。标签是通过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_categorytagged_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


    【解决方案1】:

    首先将您的category_ids 放入一个数组中

    category_ids = JobCategory.order('priority DESC').pluck(:id)
    

    然后将passing in arguments 以数组格式添加到您的作用域。这是subset conditions

    scope :by_category, ->(category_ids) {    
         where(job_category_id: category_ids)
      }
    

    我检查了your profile 并鉴于您之前在 ruby​​ on rails 上的经验,我相信您在计算其余代码时不会遇到问题

    谢谢!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多