小编bdo*_*gie的帖子

如何查询存储在数组中的Rails ActiveRecord数据

我有一个rails模型调用MentorData,它有一个名为的属性os_usage.ose存储在这样的数组中['apple', 'linux'].

回顾一下:

$ MentorData.first.os_usage
=> ['apple',  'linux']
Run Code Online (Sandbox Code Playgroud)

我希望能够查询包含os_usage的所有MentorData的数据apple,但是当我搜索时,MentorData.where(os_usage: 'apple')我只会得到只能使用apple而不是apple和linux的导师.我需要以某种方式搜索,检查数组中是否包含apple.

我也试过以下.

MentorData.where('os_usage like ?', 'apple’)
MentorData.where('os_usage contains ?', 'apple’)
MentorData.where('os_usage contains @>ARRAY[?]', 'apple')
Run Code Online (Sandbox Code Playgroud)

是否可以通过具有数组或项的属性在ActiveRecord中查询数据?

如果这有助于提供更原始的搜索查询,则数据库位于Postgres上.

ruby sql postgresql activerecord ruby-on-rails

12
推荐指数
2
解决办法
8822
查看次数

标签 统计

activerecord ×1

postgresql ×1

ruby ×1

ruby-on-rails ×1

sql ×1