Mad*_*s E 2 postgresql activerecord ruby-on-rails ruby-on-rails-4 rails-activerecord
我正在使用带有postgres db的rails 4,我正在尝试使用数组.但我不能让我的查询工作.
到目前为止我有这个:
@contacts = current_firm.contacts.order(:name)
Run Code Online (Sandbox Code Playgroud)
并且想在查询中添加一个params [:show],因此它只显示在contactType列中带有例如'place'的记录.如果网址是联系人?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
Run Code Online (Sandbox Code Playgroud)
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
>
]>
Run Code Online (Sandbox Code Playgroud)
您希望使用postgresql运算符&&(数组重叠运算符)来查看params散列与表中数据之间是否有任何值重叠.
@contacts = current_firm.contacts.order(:name).where("ARRAY[?]::varchar[] && contactType", params[:show])
Run Code Online (Sandbox Code Playgroud)
params散列应该是text []类型,而contactType记录的类型是varchar [],所以你需要转换传入的params散列以匹配postgres的contactType记录以不抛出错误.
请参阅此处的文档: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
| 归档时间: |
|
| 查看次数: |
4814 次 |
| 最近记录: |