Home > OS >  Add two ActiveRecord::Relation / scopes
Add two ActiveRecord::Relation / scopes

Time:12-15

I have two scopes.

scope :has_food_preference, -> { where.not(food_preference: nil) }

scope :wine_chosen, -> { where(relationship: 1, company_size: 1).where.not(wine_id: nil) }

So basically it's a program to organize christmas gifts for a company's customers (i do this for my father's company just for fun).

The scope has_food_preference is pretty straight forward; vegetarian, vegan, etc. Then the scope wine_chosen: only companies with a relationship: 1 and company_size: 1 will get a wine (per person that's why size matters), so the wine_id also cannot be empty.

How can I combine these two scopes?

At the end I want "All companies where food_preference is set and where wine_id is set if relationship: 1 and company_size: 1".

I tried many different things.

Option 1:

Customer.where.not(food_preference: nil).or(Customer.where(relationship: 1, company_size: 1).where.not(wine_id: nil))

--> Does not work. Completely ignores the or and only returns where.not(food_preference: nil)

Option 2:

companies = has_food_preference   wine_chosen

--> return Array. I want a ActiveRecord::Relation

Option 3:

scope :food_and_wine, -> { self.has_food_preference.merge(self. wine_chosen) }

--> Merge somehow acts like AND, but I want OR

Option 4: Something with arel_table. Had the same result as Option 1.


So HOW do I combine these two? It can't be that hard, right???

CodePudding user response:

I would expect this to work:

scope :food_and_wine, -> { has_food_preference.or(self.wine_chosen) }

CodePudding user response:

One option would be to create a scope that combines the two scopes with an OR condition:

scope :food_and_wine, -> { has_food_preference.or(wine_chosen) }

This would return customers that have a food preference or that have a relationship of 1 and a company size of 1 and a wine_id set.

Alternatively, you could create a scope that includes both conditions in the same query:

scope :food_and_wine, -> { where.not(food_preference: nil).or(where(relationship: 1, company_size: 1).where.not(wine_id: nil)) }

This would also return customers that have a food preference or that have a relationship of 1 and a company size of 1 and a wine_id set.

  • Related