SQL链(加入和支持) - Ruby

时间:2013-05-28 17:34:54

标签: sql ruby-on-rails ruby join where

我正在尝试创建一个搜索过滤器,所有参数都是复选框的名称,因此它们是填充了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和。错误......

1 个答案:

答案 0 :(得分: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)

<强>加成

部件的细节取决于模型的关系 列名没有反映出来(至少不是RoR风格) 如果是公司belongs_to :benefit_type, foreign_key: "id_benefit_type",我的第一个例子就可以了(公司的表格会有一列id_benefit_type)。

如果公司has_and_belongs_to_many :benefitsBenefit有属性id_benefit_type,则需要加入:

@companies = @companies.joins(:benefits).where(:benefits => {id_benefit_type: filter_benefit_type}) if filter_benefit_type.present?