在rails 5中的LIKE查询不起作用

时间:2017-06-20 14:25:52

标签: mysql ruby-on-rails ruby

使用此:

.. .where("field1 IN(?) AND field2 LIKE(?) AND field3 LIKE(?) ", params[:array_for_field1], "%#{params[:array_for_field2]}%", "%#{params[:array_for_field3]}%")

我得到了这个:

SELECT `table`.* FROM `table` WHERE(field1 IN('value1','value2','value3') AND field2 LIKE('%[\"value1\", \"value2\"]%') AND field3 LIKE('%[\"value1\"]%') )

我想知道错误在哪里,因为field1有效,但使用%的“LIKE Query”部分不是,params来自复选框形式。谢谢

2 个答案:

答案 0 :(得分:1)

我最终在REGEX中使用此解决方案,它可以根据需要运行。

.where("field1 IN(?) AND field2 RLIKE(?) AND field3 RLIKE(?) ", params[:array_for_field1], params[:array_for_field2].join("|"), params[:array_for_field3].join("|"))

答案 1 :(得分:0)

根据this response,如果您使用Postgres,您可以尝试这样的事情:

field2_ilike_params = params[:array_for_field2].map { |p| "%p%" }
field3_ilike_params = params[:array_for_field3].map { |p| "%p%" }
Model.where(field1: params[:array_for_field1]).where("field2 ILIKE ANY ( array[?] ) AND field3 ILIKE ANY ( array[?] )", field2_ilike_params, field3_ilike_params)