【问题标题】:How to search a postgres JSONb column with wildcards in ruby activerecord如何在 ruby​​ activerecord 中使用通配符搜索 postgres JSONb 列
【发布时间】:2016-04-01 19:00:50
【问题描述】:

我有一个包含 JSONb 列(元数据)的 postgres 表(用户)。目前我正在通过电子邮件搜索用户,它工作得很好,除了电子邮件必须完全匹配。

因此,如果用户有电子邮件 bob@smith.com 而我有 User.by_email("bob@smith.com"),那么它就很有效。但我希望User.by_email("@smith.com") 向所有用户返回一封匹配的电子邮件。

在我的 user.rb 模型中,我有以下内容:

scope :by_email, ->(email) { where("metadata @> ?", { session: { Primary: { Email: email.to_s.downcase} } }.to_json) }

这是允许User.by_email(email) 工作的原因。如何修改它以查找所有电子邮件与传入的字符串匹配的用户?

对此的第二部分是我也希望能够按用户名进行搜索。

这将通过scope :by_name, ->(name) { where("metadata @> ?", { session: { Primary: { FullName: name.to_s} } }.to_json) } 完成

我怎样才能同时做到这两点?如果这只是简单的 activerecord,我知道我可以做到:

User.where("full_name LIKE ? OR email LIKE", "%#{search}%","%#{search}%")

如何使用 JSONb 列做到这一点?

【问题讨论】:

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


    【解决方案1】:

    你可以这样做:

    User.where("metadata->'session'->'Primary'->>'Email' LIKE ?", '%@smith.com')
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    相关资源
    最近更新 更多