如何在原始查询中使用动态数组的id(rails + postgres)?

时间:2017-07-28 07:52:21

标签: ruby-on-rails postgresql

我有这段代码

Language.all.map{|l|[l.language, l.accounts.joins(:children).where("accounts.id IN (?)", @accounts.ids).uniq.count]}

我想把它作为输出

[["eng", 5] ["span", 3] ["ital", 4] ... ]

我想把它写成原始查询。

我试过了,

ActiveRecord::Base.connection.execute("select languages.language, (SELECT COUNT(*) FROM accounts where accounts.language_id = languages.id) from languages").values

但我需要传递accounts.ids动态..像这样

select languages.language, (SELECT COUNT(*) FROM accounts where accounts.language_id = languages.id AND (accounts.id IN (#{@accounts.ids})) from languages"

当我试图通过accounts.id IN #{@accounts.ids}时,我收到了错误消息 (accounts.id IN ([2839, 284.. ..这应该是IN (2839, 284..),而是采用数组。

如何动态传递它?

3 个答案:

答案 0 :(得分:2)

您可以尝试:

"... accounts.id IN (#{@accounts.ids.join(',')})"

希望它有所帮助。

答案 1 :(得分:0)

您可以使用where(id: @accounts.ids)where("account.ids": @accounts.ids)where("account.ids IN ?, @accounts.ids)。我相信ActiveRecord应该了解所有这些。

答案 2 :(得分:0)

如果您尝试在原始sql查询中使用字符串数组,则以上2个答案将不起作用。对于原始sql语句,可以使用ActiveRecord的sanitize_sql_array方法。

languages = ['eng', 'span', 'chin', 'ital']
base_query = "SELECT * FROM languages WHERE id IN (?)"
sanitized_query = ActiveRecord::Base.send :sanitize_sql_array, [base_query, languages]
ActiveRecord::Base.connection.execute(sanitized_query)