假设我有一个带有名为“name”的 json 数组属性的 Product 表。例如,Product.first.name == ["large", "black", "hoodie"]
。我想在我的数据库中搜索名称中包含搜索查询中的单词的产品。所以如果我输入“大连帽衫”,Product.first 应该在结果中返回。
所以首先我必须把搜索键变成一个字符串数组:
def search
search_array = params[:search].split(" ")
results = #???
但是如何搜索名称中包含值的产品search_array
?我找到了关于如何在数组中搜索值的文档,但没有找到关于如何搜索数组本身的文档。
您可以简单地使用,@>
(包含)运算符。
select * from products;
id | name | tags | created_at | updated_at
----+---------+--------------------------------+----------------------------+----------------------------
3 | T-Shirt | {clothing,summer} | 2017-10-30 05:28:19.394888 | 2017-10-30 05:28:19.394888
4 | Sweater | {clothing,winter,large,hoodie} | 2017-10-30 05:28:38.189589 | 2017-10-30 05:28:38.189589
(2 rows)
select * from products where tags @> '{large, hoodie}';
id | name | tags | created_at | updated_at
----+---------+--------------------------------+----------------------------+----------------------------
4 | Sweater | {clothing,winter,large,hoodie} | 2017-10-30 05:28:38.189589 | 2017-10-30 05:28:38.189589
(1 row)
或者,作为 AR 查询,
2.3.1 :002 > Product.where("tags @> '{large, hoodie}'")
Product Load (0.4ms) SELECT "products".* FROM "products" WHERE (tags @> '{large, hoodie}')
=> #<ActiveRecord::Relation [#<Product id: 4, name: "Sweater", tags: ["clothing", "winter", "large", "hoodie"], created_at: "2017-10-30 05:28:38", updated_at: "2017-10-30 05:28:38">]>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句