Rails 4 Active Record数组查询

时间:2013-06-29 10:17:13

标签: ruby-on-rails postgresql activerecord rails-activerecord ruby-on-rails-4

我正在使用带有postgres db的rails 4,并且我正在尝试使用数组。 但我无法让我的查询工作。

到目前为止,我有这个:

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

并且想在查询中添加一个params [:show],因此它只显示带有例如的记录。 '地方'在contactType列中。如果网址是联系人?show = place。

我真的希望你能提供帮助,因为我现在已经试着解决这个问题了几个小时。

架构:

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

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
  >
]>

3 个答案:

答案 0 :(得分:5)

您想使用postgresql运算符&amp;&amp; (数组重叠运算符)以查看params散列与表中数据之间是否有任何值重叠。

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

params散列应该是text []类型,而contactType记录的类型是varchar [],所以你需要转换传入的params散列以匹配postgres的contactType记录,以免抛出错误。< / p>

请参阅此处的文档: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

答案 1 :(得分:3)

@contacts = current_firm.contacts.where("'?' = ANY (contactType)", params[:show]).order(:name)

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

答案 2 :(得分:1)

@contacts = current_firm.contacts.where.contains(contactType: [params[:show]]).order(:name)

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