[英]How do I query ActiveRecord to return only the first instance of each object where enum = X, Y, Z?
[英]how to make a ruby array be a x,y,z in an ActiveRecord prepared statement
我在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
我希望能夠傳遞一個從1到10的值數組(作為任意上限),並能夠使用postgres ilike語句針對我們的表進行查詢。
但我明白了
ActiveRecord :: PreparedStatementInvalid:錯誤的綁定變量數(1為2)位於:metro_area_ids ilike'%-?-%'或metro_area_ids ilike'%-?-%'
對於數組中任意數量的輸入,我將如何使其工作?
所以這不起作用
Queryable.where("metro_area_ids ilike '%-?-%' or metro_area_ids ilike '%-?-%'",[1,13])
所以這確實有效,這就是我要模擬的內容:
Queryable.where("metro_area_ids ilike '%-?-%' or metro_area_ids ilike '%-?-%'",1,13)
這是因為您通過?
引用了許多參數?
僅指定一個(字符串)時,請使用命名的占位符或單獨指定數組的每個元素。
使用命名占位符
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)
分開提供每個元素
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])
您只需通過$ 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.