2

I'm using rails 4 with postgres db, and im trying out array. But I can't get my query to work.

I have this so far:

@contacts = current_firm.contacts.order(:name)

and would like to add a params[:show] to the query, so it only shows the records with e.g. 'place' in the contactType column. if the url is contacts?show=place.

I really hope you can help, because I have tried to figure this out for hours now.

Schema:

create_table "contacts", force: true do |t|
  t.integer  "firm_id"
  t.string   "contactType",                 array: true
  t.string   "name"
  t.string   "adress"
  t.integer  "zipcode"
  t.string   "town"
  t.string   "country",     default: "DK"
  t.integer  "cvr"
  t.string   "email"
  t.string   "contact"
  t.string   "phone"
  t.string   "cellPhone"
  t.string   "website"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.boolean  "deleteFlag",  default: false
end

Console dump of Contact.all

#<ActiveRecord::Relation 
  [#<
    Contact id: 7, 
    firm_id: 5, 
    contactType: ["customer", "place"], 
    name: "PA Syd", 
    adress: "", 
    zipcode: nil, 
    town: "", 
    country: "DK", 
    cvr: nil, email: "", 
    contact: "Lars Opstrup", 
    phone: "", 
    cellPhone: nil, 
    website: "", 
    created_at: "2013-06-28 13:29:18", 
    updated_at: "2013-06-28 13:29:18", 
    deleteFlag: false
  >, 
  #<
    Contact id: 1, 
    firm_id: 5, 
    contactType: ["place"], 
    name: "Mads Ellesgaard", 
    adress: "", 
    zipcode: 6400, 
    town: "Soenderborg", 
    country: "DK", 
    cvr: nil, 
    email: "mads@example.dk", 
    contact: "", 
    phone: "", 
    cellPhone: nil, 
    website: "", 
    created_at: "2013-06-28 11:58:58", 
    updated_at: "2013-06-29 09:35:39", 
    deleteFlag: false
  >
]>
4

3 回答 3

5

您想使用 postgresql 运算符 &&(数组重叠运算符)来查看参数哈希和表中的数据之间是否有任何值重叠。

@contacts = current_firm.contacts.order(:name).where("ARRAY[?]::varchar[] && contactType", params[:show])

params 散列应该是 text[] 类型,而 contactType 记录是 varchar[] 类型,因此您需要转换传入的 params 散列以匹配 contactType 记录的散列,以便 postgres 不会引发错误。

请参阅此处的文档:http ://www.postgresql.org/docs/9.2/static/functions-array.html

如果您有许多这些类型的查询,您可能还想查看 postgres_ext gem,尽管对于这个用例,它可能会产生过多的开销:https ://github.com/dockyard/postgres_ext/blob/master/docs/querying .md

于 2013-06-30T05:35:46.270 回答
3
@contacts = current_firm.contacts.where("'?' = ANY (contactType)", params[:show]).order(:name)

我没有测试它,但它应该可以工作。

于 2013-06-29T10:25:21.397 回答
1
@contacts = current_firm.contacts.where.contains(contactType: [params[:show]]).order(:name)

见:https ://viget.com/extend/searching-serialized-fields-in-rails-using-postgres-arrays

于 2015-12-30T14:59:21.250 回答