ruby-on-rails - 如何查询Noticed gem json字段

标签 ruby-on-rails ruby

我正在使用Noticed gem 获取我的通知,我正在尝试查询与该帖子相关的通知。 通知将帖子存储为参数内的对象。

#<Notification id: 10, params: {:post=>#<Post id: 3}>

我可以像这样定位

notification.params[:post][:id] 
=> 3

我想要完成的是这样的事情:

Notifications.where(params[:post][:id] => 3)

有没有办法做到这一点,或者我的方法应该不同?

已编辑:

以下是数据库中的通知示例:

#<Notification id: 10, recipient_type: "User", recipient_id: 8, type: "MessageNotification", params: {:user=>#<User id: 3, email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1b5a4b2b5f381b5a4b2b5f3efa2aeac" rel="noreferrer noopener nofollow">[email protected]</a>", created_at: "2021-01-06 23:34:46", updated_at: "2021-04-15 17:47:54", admin: true>, :conversation=>#<Mailboxer::Conversation id: 6, subject: "Hello", created_at: "2021-05-14 00:14:41", updated_at: "2021-05-14 00:26:06">}, read_at: nil, created_at: "2021-05-14 00:26:06", updated_at: "2021-05-14 17:11:50">

squema.rb

t.jsonb "params"

@Joel_Blum 和 slq 调用建议的查询:

>> current_user.notifications.where('params @> ?', {conversation: {id: 6}}.to_json).to_sql
=> "SELECT \"notifications\".* FROM \"notifications\" WHERE \"notifications\".\"recipient_id\" = 8 AND \"notifications\".\"recipient_type\" = 'User' AND (params @> '{\"conversation\":{\"id\":6}}')"

Returns => #<ActiveRecord::AssociationRelation []>

最佳答案

gem 似乎创建了 jsonb or json column取决于你的数据库。 所以想要的是在 json(b) 列上执行搜索

例如对于 postgres 可以这样做

Notification.where('params @> ?', {post: {id: 3}}.to_json)

关于ruby-on-rails - 如何查询Noticed gem json字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67539518/

相关文章:

css - 显示电话号码的无序列表

ruby-on-rails - 如何在 Rails 中实现 Rouge 语法高亮?

ruby-on-rails - 在 Rails 中使用 include 时,排序方式不会排序

ruby-on-rails - 加载 'sqlite3' Active Record 适配器时出错。当我在 Heroku 中部署时

ruby-on-rails - Formastic,ActiveAdmin 添加 javascript

ruby - 安装带有 Rails : "Could not find "Nokogiri. 的 Nokogiri Gem 的问题 .."

ruby - 瓦蒂尔。滚动到页面的某个点

html - Ruby on Rails/HTML - 内联表单 :checked => false is not working

jquery - 使用 Rails link_to 禁用 Ajax 调用

mysql - 使用 simple_form 在 Rails 中自定义日期时间字段