简体   繁体   English

如何在ActiveRecord准备好的语句中使ruby数组为ax,y,z

[英]how to make a ruby array be a x,y,z in an ActiveRecord prepared statement

I am using Ruby on Rails 3.20 and Postgres 9.4 on heroku and have the following fragement: 我在heroku上使用Ruby on Rails 3.20和Postgres 9.4,并且有以下问题:

metro_area_ids=[3,4,7]
a=metro_area_ids.join(',')
self.where("metro_area_ids ilike '%-?-%' or metro_area_ids ilike '%-?-%' or metro_area_ids='%-?-%'", a)  # how to make this array be 3,4,7 joining doesn't work

I'd like to be able to pass an array of values from 1 to 10 (as an arbitrary upper limit) and be able to query against our table with a postgres ilike statement. 我希望能够传递一个从1到10的值数组(作为任意上限),并能够使用postgres ilike语句针对我们的表进行查询。

but I get 但我明白了

ActiveRecord::PreparedStatementInvalid: wrong number of bind variables (1 for 2) in: metro_area_ids ilike '%-?-%' or metro_area_ids ilike '%-?-%' ActiveRecord :: PreparedStatementInvalid:错误的绑定变量数(1为2)位于:metro_area_ids ilike'%-?-%'或metro_area_ids ilike'%-?-%'

How would I make this work for an arbitrary number of inputs in the array? 对于数组中任意数量的输入,我将如何使其工作?

edit 编辑

so this doesn't work 所以这不起作用

Queryable.where("metro_area_ids ilike '%-?-%' or metro_area_ids ilike '%-?-%'",[1,13])

so this does work which is what I'm trying to simulate: 所以这确实有效,这就是我要模拟的内容:

Queryable.where("metro_area_ids ilike '%-?-%' or metro_area_ids ilike '%-?-%'",1,13)

This is because you reference many arguments through ? 这是因为您通过?引用了许多参数? while specifying only one (a string), use named placeholders or specify every element of the array alone. 仅指定一个(字符串)时,请使用命名的占位符或单独指定数组的每个元素。

using named placeholders 使用命名占位符

metro_area_ids={ st: 3, nd: 4, th: 7 }
self.where("metro_area_ids ilike '%-:st-%' or metro_area_ids ilike '%-:nd-%' or metro_area_ids='%-:th-%'", metro_area_ids) 

provide each element separatly 分开提供每个元素

self.where("metro_area_ids ilike '%-?-%' or metro_area_ids ilike '%-?-%' or metro_area_ids='%-?-%'", metro_area_ids[0], metro_area_ids[1], metro_area_ids[2]) 

you can simply test it by $ ruby test.rb and copy following content to the file 您只需通过$ ruby test.rb测试,然后将以下内容复制到文件中

require 'active_record'

class Metro < ActiveRecord::Base
  establish_connection adapter: 'sqlite3', database: 'foobar.db'
  connection.create_table table_name, force: true do |t|
    t.string :metro_area_ids
  end
end

Metro.create!([
  { metro_area_ids: '1,2,3,4' },
  { metro_area_ids: '2,3,4,5' },
  { metro_area_ids: '3,4,5,6' },
])
metros = Metro.where("metro_area_ids LIKE ?", "%2,3%")
p metros.inspect
#=> [#<Metro id: 1, metro_area_ids: \"1,2,3,4\">,
     #<Metro id: 2, metro_area_ids: \"2,3,4,5\">]

像这样:

Queryable.where("metro_area_ids ilike '?' or metro_area_ids ilike '?'", "%-#{1}-%", "%-#{13}-%")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM