Rails结合了多个activerecord关系

时间:2014-04-28 08:36:58

标签: ruby ruby-on-rails-4 rails-activerecord activerecord-relation

我想结合多个活动记录关系

例如,

apple_companies = Company.where("name like ?","%apple%")
banana_companies = Company.where("name like ?","%banana%")

我想结合这两种关系。

不合并,合并是      apple_companies.merge(banana_companies) => Company.where(“名字喜欢?和名字一样?”,“%apple%”,“%banana%”)

我想      Company.where(“名字喜欢?或名字喜欢?”,“%apple%”,“%banana%”)

之后,

我会编码

companies = Company.none
company_name_list.each do |name|
    like = "%"+name+"%"
    companies += Company.where("name like ?",like)
end

但是我编写的代码使公司成为数组......

所以我无法订购和寻找公司...... :(

谢谢

6 个答案:

答案 0 :(得分:4)

apple_companies = Company.where("name like ?","%apple%")
banana_companies = Company.where("name like ?","%banana%")

apples = apple_companies.where_values.reduce(:and)
bananas = banana_companies.where_values.reduce(:and)

Company.where(apples.or(bananas))

有关更多示例,请参阅ActiveRecord Arel OR condition

答案 1 :(得分:4)

我遇到的最佳结果是抓取并合并两个查询的ID,然后像这样搜索它们:

apple_companies = Company.where("name like ?","%apple%").pluck(:id)
banana_companies = Company.where("name like ?","%banana%").pluck(:id)
ids = apple_companies + banana_companies.uniq
Company.where(id: ids)

它的四条线看起来应该可以在一条线上运行但是有效。

答案 2 :(得分:2)

在这种情况下,您可以使用任何其他答案。但是在更一般的情况下,我强烈建议使用any_of gem。有了这个宝石,你可以做到:

apple_companies = Company.where("name like ?","%apple%")
banana_companies = Company.where("name like ?","%banana%")

Company.where.any_of(apple_companies, banana_companies)

已经有pull request将此功能添加到未来的rails版本中。

答案 3 :(得分:1)

请尝试使用

Company.where('name LIKE ? OR name LIKE ?','%apple%', '%banana%')

OR

Company.where('name IN (?)', ['%apple%', '%banana%'])

根据你的代码:

names = []
company_name_list.each do |name|
    names << "%"+name+"%"
end

然后你可以这样做:

companies = Company.where('name LIKE ANY(Array[?])', names)

答案 4 :(得分:0)

迟到的答案,但Arel会解决它。

Company.where(Company.arel_table[:name].matches_any(["%apple%", "%banana%"]))

答案 5 :(得分:-1)

使用

Company.where(name: IN ('%apple%','%banana%'))