2

我使用rails 4与postgres数据库,并试图数组。 但我无法让我的查询工作。Rails 4活动记录数组查询

我有这个至今:

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

,并想添加一个PARAMS [:秀]到查询,所以只显示了例如记录'放置'在contactType列中。如果url是contacts?show = place。

我真的希望你能帮上忙,因为我已经试着想出了几个小时了。

模式:Contact.all

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 

控制台转储

#<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: "[email protected]", 
    contact: "", 
    phone: "", 
    cellPhone: nil, 
    website: "", 
    created_at: "2013-06-28 11:58:58", 
    updated_at: "2013-06-29 09:35:39", 
    deleteFlag: false 
    > 
]> 

回答

5

想要使用postgresql运算符& &(数组重叠运算符)来查看是否有任何值在表中的params散列值和数据之间重叠。

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

params哈希表的类型应该为文本[],而contactType记录的类型为varchar [],所以你需要转换传入PARAMS哈希以匹配contactType记录的Postgres的不抛一个错误。

在这里看到的文档:http://www.postgresql.org/docs/9.2/static/functions-array.html

你可能也想看看,如果你有很多这些类型的查询的postgres_ext宝石,虽然这种使用情况下,它可能是过多的开销:https://github.com/dockyard/postgres_ext/blob/master/docs/querying.md

+0

非常感谢!这是一个很好的帮助,我只需要将我的列从contactType重命名为contact_type,它就可以工作。 –

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

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

+0

事实证明了这一点: PG ::错误:错误:列 “客户” 不存在LINE 1: “ ”...... eteFlag” = 'f' 和“ 人脉firm_id”= $ 1和(客户= ... ^ :SELECT“contacts”。* FROM“contacts”WHERE“contacts”。“deleteFlag”='f'AND“contacts”。“firm_id”= $ 1 AND(customer = ANY(contactType))ORDER BY“contacts” .name ASC –

+0

if if @contacts = current_firm.contacts.where(“(contactType)= ANY'#{params [:show]}'”)。order(:name) –

+0

我得到: PG :: Error :'ERROR:语法错误在''customer'或'near'' –