0

我正在尝试创建一个搜索过滤器,所有参数都是复选框的名称,因此它们是填充了 id 值的数组。

@sql_query = ''

if filters_benefit_type.nil? == false
  @sql_query = 'id_benefit_type = (:benefit_types)'
end

if filters_category.nil? == false
  if filters_benefit_type.nil? == false
    @sql_query = @sql_query + ' AND '
  end
  @sql_query = @sql_query + 'id_subcategory = (:company_subcategorys)'
end

if filters_zone.nil? == false
  if filters_category.nil? == false
    @sql_query = @sql_query + ' AND '
  end
  @sql_query = 'zone = (:zones)'
end

@companys = Company
  .joins(:subsidiary)
  .joins(:benefit)
  .where(@sql_query, 
    :benefit_types => filters_benefit_type, 
    :company_subcategorys => filters_category, 
    :zones => filters_zone
  )

这引发了以下错误:

Mysql2::Error: Operand should contain 1 column(s):

有任何想法吗 ?我想我在做 .joins 和 .where 错误...

4

1 回答 1

1

尝试链接关系:

@companies = Company.scoped
@companies = @companies.where(id_benefit_type: filter_benefit_type) if filter_benefit_type.present?
@companies = @companies.where(id_subcategory: filter_category) if filter_category.present?
@companies = @companies.where(zone: filter_zone) if filter_zone.present?

只要过滤器是空的或整数数组!

where(column: [1,2,3])给出条件where column in (1,2,3)

添加

where 部分的详细信息取决于模型的关系。
列名没有反映这一点(至少,不是在 RoR 样式中)。
如果 ie Company belongs_to :benefit_type, foreign_key: "id_benefit_type",我的第一个示例将起作用(公司表将有一个 column id_benefit_type)。

如果 Company has_and_belongs_to_many :benefits,并且Benefit有一个属性id_benefit_type,你将需要一个连接:

@companies = @companies.joins(:benefits).where(:benefits => {id_benefit_type: filter_benefit_type}) if filter_benefit_type.present?
于 2013-05-28T18:36:09.113 回答