我正在使用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/