Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 418
user3580287 Avatar asked Apr 28 '14 08:04

user3580287


1 Answers

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.

like image 157
Jason Noble Avatar answered Nov 24 '22 06:11

Jason Noble