Ruby on rails 如何将Rails中激活记录中的多个OR和条件作为字符串传递

Ruby on rails 如何将Rails中激活记录中的多个OR和条件作为字符串传递,ruby-on-rails,activerecord,rails-activerecord,Ruby On Rails,Activerecord,Rails Activerecord,我是RubyonRails的新手,我想根据一个条件获取记录,我正在以字符串格式传递该条件。此外,我将在多个OR条件中传递查询。然而,现在,我被困在rails中如何以字符串格式传递查询 我已经附上了截图 上面的行成功执行并给出了输出 <CustomAttribute id: 18, data_type: "string", label: "Marital status", code: "marital_status", entity

我是RubyonRails的新手,我想根据一个条件获取记录,我正在以字符串格式传递该条件。此外,我将在多个OR条件中传递查询。然而,现在,我被困在rails中如何以字符串格式传递查询 我已经附上了截图

上面的行成功执行并给出了输出

<CustomAttribute id: 18, data_type: "string", label: "Marital status", code: "marital_status", entity_type: "member", company_id: 1, created_at: "2021-03-10 10:16:15", updated_at: "2021-03-10 10:16:27", is_active: true, is_default: false, rank: nil, is_identifier: false>
错误:“单一”列不存在

这是我想计算的值

这是我创建动态查询的代码

logical_operator = 'OR'
  @custom_attribute = CustomAttribute.includes(:custom_attribute_values).where(id: custom_attribute_ids, company_id: current_user.company_id)

  query=""
  @custom_attribute.each_with_index do |attribute_object, index|

    filter_object= filter_params[:filters].find {|x| x['custom_attribute_id']==attribute_object['id']}

    if filter_object.present?
      query +=  "("+ '"' +'value_'+attribute_object.data_type + '"' + ' ' + filter_object['operator'] + ' ' + "'" +  filter_object['value'].to_s + "'"+ ")"
    end

    if index != @custom_attribute.length-1
      query+=' '+logical_operator+' '
    end

    if index == @custom_attribute.length-1
      query="'" + " ( " +  query + " ) " + "'"
    end

  end
  byebug
  
  puts(@custom_attribute.first.custom_attribute_values.where(query).size)

任何时候在Ruby中进行大量转义和字符串添加都是错误的。如果我们清理您构建SQL的方式:

"\""+"value_string"+"\""+"="+"\""+'Single'+"\""
事情会更清楚。首先,在操作符周围留出空间以便于阅读:

"\"" + "value_string" + "\"" + "=" + "\"" + 'Single' + "\""
接下来,除非转义码(如
\n
)或插值需要双引号,否则不要使用双引号:

'"' + 'value_string' + '"' + '=' + '"' + 'Single' + '"'
现在我们看到我们正在添加几个常量字符串,因此根本不需要添加它们,一个字符串文字就可以:

'"value_string" = "Single"'
标准SQL对标识符(如表名和列名)使用双引号,对字符串使用单引号。因此,您的查询要求所有行的
value\u字符串
列等于
Single
列,这就是您的错误

您希望对字符串使用单引号(以及
%q(…)
来引用整个内容,以避免在中添加转义):

或者更好,让ActiveRecord生成查询:

# With a positional placeholder:
@data.custom_attribute_values.where('value_string = ?', 'Single')

# Or a named placeholder:
@data.custom_attribute_values.where('value_string = :s', s: 'Single')

# Or most idiomatic:
@data.custom_attribute_values.where(value_string: 'Single')

非常感谢您提供的解决方案,现在它正在发挥作用
'"value_string" = "Single"'
@data.custom_attribute_values.where(
  %q("value_string" = 'Single')
)
# With a positional placeholder:
@data.custom_attribute_values.where('value_string = ?', 'Single')

# Or a named placeholder:
@data.custom_attribute_values.where('value_string = :s', s: 'Single')

# Or most idiomatic:
@data.custom_attribute_values.where(value_string: 'Single')