【问题标题】:How to find records where a column value = [given array] in rails如何在rails中查找列值= [给定数组]的记录
【发布时间】:2017-02-14 04:33:28
【问题描述】:

设置: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 子句中传递多个列,其中一些列是数组类型。对于 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 子句中将它们作为散列/条件传递是行不通的。

【问题讨论】:

  • 在检查并点击插入查询之前需要忽略哪些列..?
  • 上面定义的 ignore_attributes 数组中的那些。

标签: ruby-on-rails postgresql rails-activerecord


【解决方案1】:

使用 find_by 来查找_all_by,它会返回所有匹配的结果。

【讨论】:

    【解决方案2】:

    试试这个例子:-

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

    希望对你有帮助:)

    【讨论】:

    • 谢谢,但我不想按单列查找,我想在 where 子句中传递多个值的散列(在问题中说明相同)
    • 你能分享任何例子吗......会尽力帮助你吗?)
    • 添加了有问题的示例@milind
    • 我已经更新了我的答案..如果有帮助请告诉我
    【解决方案3】:

    您在 rails 中的查询如下所示

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

    【讨论】:

    • 没听懂你想说的。你上面写的和我的问题一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多