gpt4 book ai didi

ruby-on-rails - Rails 4 事件记录数组查询

转载 作者:行者123 更新时间:2023-11-29 11:53:20 25 4
gpt4 key购买 nike

我将 Rails 4 与 postgres 数据库一起使用,我正在尝试数组。但是我的查询无法正常工作。

到目前为止我有这个:

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

并想在查询中添加一个 params[:show] ,所以它只显示带有 e.g. 的记录。 “放置”在 contactType 列中。如果 url 是 contacts?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
>
]>

最佳答案

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

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

params hash 应该是 text[] 类型,而 contactType 记录是 varchar[] 类型,所以你需要转换传入的 params hash 来匹配 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

关于ruby-on-rails - Rails 4 事件记录数组查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17379123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com