设置:Rails + Postgres。如何在rails中找到列值= [给定数组]的记录
我有列
id: int, name: string, address: string, s_array: varchar[], i_array: int[], created_at: datetime)
对于行的表A,我需要找到所有具有类似值的行。 在轨,然后查询看起来像
row = A.find(1) # any random row
ignore_columns = %w[id created_at]
A.where(row.attributes.except(*ignore_columns))
,如果我们没有与数组类型的列这工作。 如何查找值为[给定数组]的所有记录?
编辑: 要清楚,我想在where子句中传递多个列,其中某些列是数组类型。对于其中子句中值,我传递散列(row.attributes.except(* ignore_columns)是哈希)
编辑2:实施例:
可以说我有一个查询表
Query(id: Int, name: String, terms: varchar[], filters: int[], city: string, created_at: datetime)
id = primary key/integer
terms = array of string
filters = array of integer (it is an enum and we can select multiple which is saved as array)
other fields = self explanatory
假设我有以下行
(1, "query1", ["john"], [0], "wall", <some_date>)
(1, "query2", ["eddard", "arya"], [0, 1], "Winterfell", <some_date>)
(1, "query3", ["sansa", "arya"], [1, 2], "Winterfell", <some_date>)
现在,当我添加新行
row = ActiveRecord of (1, "query4", ["eddard", "arya"], [0, 1], "Winterfell", <some_date>)
我想是搜索已经存在的记录是这样
ignore_attributes = %w[id name created_at]
Query.where(row.attributes.except(*ignore_attributes))
此查询应该返回已有QUERY3这样我就不需要与名query4添加新行。
问题是,因为某些列类型是数组类型,然后将它们作为散列/条件传递给where子句不起作用。
在检查并点击插入查询之前,您需要忽略哪些列。 – Milind
上面定义的ignore_attributes数组中的那些。 – chinmayv