在quoted_pa​​rameters(params)中使用空参数

时间:2016-02-22 18:11:51

标签: ruby-on-rails rails-activerecord pg

我有以下代码:

pg = ActiveRecord::Base.connection
res = pg.execute(query % quoted_parameters(params))

这是我的伪查询:

select project_id from projects where client_id in (%{ids})

这是参数:

{ :ids => [] }

当ids数组中有实际值时,它可以正常工作。但是它似乎无法处理空数组,我得到了:

ERROR:  syntax error at or near ")"

因为它只是放入一个空字符串。

默认情况下,这样可以正常工作:

Project.where('client_id in (?)', [])

并生成以下查询:

Project Load (3.5ms)  SELECT "projects".* FROM "projects"  WHERE (client_id in (NULL))

有没有办法让查询%quoted_pa​​rameters(params)生成相同的查询,即使数组是空的?

1 个答案:

答案 0 :(得分:0)

澄清:您是否尝试在应用中手动使用SQL?或者询问如何使用AR实现这一目标?

使用ActiveRecord,您应该可以:

Project.where(client_id: ids)

这可以在很多情况下使用:

Project.where(client_id: [])
=> SELECT "projects".* FROM "projects" WHERE 1=0

Project.where(client_id: [1])
=> SELECT "projects".* FROM "projects" WHERE "projects"."client_id" = 1

Project.where(client_id: [1, 2])
=> SELECT "projects".* FROM "projects" WHERE "projects"."client_id" IN (1, 2)