2017-02-14 46 views
3

设置: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子句不起作用。

+0

在检查并点击插入查询之前,您需要忽略哪些列。 – Milind

+0

上面定义的ignore_attributes数组中的那些。 – chinmayv

回答

0

你在铁轨查询类似于下面

row = A.find(1) 

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

A.where(where_clauses) 
+0

没有得到你想说的话。你上面写的和我的问题一样。 – chinmayv

0

试试这个例子: -

##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) 

希望它能帮助:)

+0

谢谢,但我不想通过单个列查找,我想在where子句中传递多个值的散列(澄清同一问题) – chinmayv

+0

可以分享任何示例...将尽力帮助您吗?) – Milind

+0

在问题中添加了示例@milind – chinmayv

0

使用find_by到find_all_by,它会返回所有匹配的结果。

相关问题