【问题标题】:Active Record Query - Search Multiple Columns for Multiple Strings and Return Only if They Are All Included活动记录查询 - 在多个列中搜索多个字符串并仅在它们都包含时才返回
【发布时间】:2013-09-23 16:27:53
【问题描述】:

我需要通过 Active Record 和 Postgresql 设计查询的帮助。

• 查询必须搜索以下列所有...

模型如下所示:

Collection

 item_id1: String
 item_id2: String
 item_id3: String
 item_id4: String
 item_id5: String
 item_id6: String

• 查询需要传入需要在所有item_id 字段中搜索的字符串数组。

• 查询还必须只返回包含数组中所有字符串的 Records 的结果。

注意:我还安装了 Textacular Full Text Search gem。但是,我测试了一个搜索,我认为只有当记录包含所有传入的字符串时才应该搜索并返回匹配项,尽管我的数据库中存在具有这些字符串的记录,但搜索结果却一无所获。像这样:Collection.advanced_search('B0066AJ5TK&B0041KJSL2')

【问题讨论】:

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


    【解决方案1】:

    澄清一下:您想要在六个item_id 字段中的某个位置找到数组中每个字符串的记录?

    可能有一种更优雅的方法可以做到这一点,但这是我的想法:

    terms = ['foo', 'bar', 'baz']
    
    conditions = []
    values = {}
    
    terms.each_with_index do |t,i|
      arg_id = "term#{i}".to_sym
       conditions << "(item_id1 = :#{arg_id} OR item_id2 = :#{arg_id} OR item_id3 = :#{arg_id} OR item_id4 = :#{arg_id} OR item_id5 = :#{arg_id} OR item_id6 = :#{arg_id})"
       values[arg_id] = t
    end
    
    Collection.where(conditions.join(' AND '), values)
    

    这应该会产生这样的查询:

    SELECT "collections".* FROM "collections" WHERE ((item_id1 = 'foo' OR item_id2 = 'foo' OR item_id3 = 'foo' OR item_id4 = 'foo' OR item_id5 = 'foo' OR item_id6 = 'foo') AND (item_id1 = 'bar' OR item_id2 = 'bar' OR item_id3 = 'bar' OR item_id4 = 'bar' OR item_id5 = 'bar' OR item_id6 = 'bar') AND (item_id1 = 'baz' OR item_id2 = 'baz' OR item_id3 = 'baz' OR item_id4 = 'baz' OR item_id5 = 'baz' OR item_id6 = 'baz'))
    

    这又长又丑,但应该得到你想要的结果。

    如果您的意思是字段可能包含要搜索的字符串,而不是等于,您可以改为使用

    item_id1 LIKE #{arg_id}
    

    values[arg_id] = "%#{t}%"
    

    【讨论】:

    • 正确,仅记录数组中的每个字符串在六个 item_id 字段中的某个位置。
    猜你喜欢
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 2018-05-05
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    • 1970-01-01
    相关资源
    最近更新 更多