Ruby on rails 如何在rails中查找列值=[给定数组]的记录

Ruby on rails 如何在rails中查找列值=[给定数组]的记录,ruby-on-rails,postgresql,rails-activerecord,Ruby On Rails,Postgresql,Rails Activerecord,设置:Rails+Postgres 我有带列的表A id: int, name: string, address: string, s_array: varchar[], i_array: int[], created_at: datetime) 对于一行,我需要找到所有具有相似值的行。 在rails中,则查询如下所示 row = A.find(1) # any random row ignore_columns = %w[id created_at] A.where(row.attribut

设置:Rails+Postgres

我有带列的表A

id: int, name: string, address: string, s_array: varchar[], i_array: int[], created_at: datetime)
对于一行,我需要找到所有具有相似值的行。 在rails中,则查询如下所示

row = A.find(1) # any random row
ignore_columns = %w[id created_at]
A.where(row.attributes.except(*ignore_columns))
如果没有数组类型的列,则此操作有效。 如何查找值=[给定数组]的所有记录

编辑: 为了清楚起见,我想在where子句中传递多个列,其中一些列的类型为array。对于where子句中的值,我传递散列(row.attributes.except(*ignore\u 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>)
这个查询应该返回已经存在的query3,这样我就不需要添加名为query4的新行


问题在于,由于某些列类型是数组类型,因此在where子句中以哈希/条件的形式传递它们是无效的

row = A.find(1)

where_clauses = row.attributes.reject{|k,v| %[id, created_at].include?(k)}

A.where(where_clauses)
试试这个例子:-

    ##black list of attributes
   ignore_attributes = %w[id name created_at]

   MyModel.where(active: true).select(MyModel.attribute_names - ignore_attributes)

   =====The above query can also be chained as:- =====

   ##you have a city column too
    MyModel.where(active: true).select(MyModel.attribute_names - ignore_attributes).where.not(:city=>["Sydney","London"])
如果需要永久修复,可以在model.rb文件中添加这一行。 但这很危险

self.ignored_columns = %w(id name created_at)

希望它有帮助:)

使用find\u by查找所有匹配的结果,它将返回所有匹配的结果。

谢谢,但我不想按单个列查找,我想在where子句中传递多个值的散列(澄清了相同的问题)你能和我分享一些例子吗?)问题中增加的例子@milindi已经更新了我的答案。如果有用的话,请告诉我。我没有明白你想说的。您上面写的内容与我的问题相同。在检查并执行插入查询之前,您需要忽略哪些列?上面定义的ignore_attributes数组中的列。
    ##black list of attributes
   ignore_attributes = %w[id name created_at]

   MyModel.where(active: true).select(MyModel.attribute_names - ignore_attributes)

   =====The above query can also be chained as:- =====

   ##you have a city column too
    MyModel.where(active: true).select(MyModel.attribute_names - ignore_attributes).where.not(:city=>["Sydney","London"])
self.ignored_columns = %w(id name created_at)