user3580287
user3580287

Reputation: 73

Rails combine multiple activerecord relations

I want to union multiple active record relation

For example,

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

I want to combine these two relation.

not merge, merge is apple_companies.merge(banana_companies) => Company.where("name like ? and name like ?", "%apple%","%banana%")

I want to Company.where("name like ? or name like ?", "%apple%","%banana%")

afterward,

I will code

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

but code which I wrote make companies to array.....

So I cannot order and page to companies... :(

thank you

Upvotes: 5

Views: 11582

Answers (6)

244an
244an

Reputation: 1589

Late answer, but Arel will solve it.

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

Upvotes: 0

Skinny
Skinny

Reputation: 91

The best result for this that I've come across is to grab and merge the ids of the two queries and then search for them like this:

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)

It's four lines that seems like it should be doable in one but it works.

Upvotes: 5

Jason Noble
Jason Noble

Reputation: 3766

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

See ActiveRecord Arel OR condition for more examples.

Upvotes: 5

manu29.d
manu29.d

Reputation: 1568

Please try using

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

OR

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

According to your code:

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

Then you can do:

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

Upvotes: 1

BroiSatse
BroiSatse

Reputation: 44685

In this case you can use any of the other answers. However in more general cases, I strongly recommend using any_of gem. With this gem you can do:

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

Company.where.any_of(apple_companies, banana_companies)

There already is a pull request to add this functionality to future rails releases.

Upvotes: 2

Babar
Babar

Reputation: 1202

Use

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

Upvotes: -1

Related Questions