How do you do a logcal or using two ActiveRelation results returning another relation
Given I have the following code
class Product < ActiveRecord::Base
def self.from_country(country)
where(:origin_country_id => country.id)
end
def self.for_country(country)
where(:destination_country_id => :country.id)
end
end
If I wa开发者_运维技巧nt products made and distributed to Germany I can do the following
Product.for_country.from_country #=> ActiveRecord::Relation
products = Product.for_country.from_country #=> Array[<Product...>...]
In the above case I can chain more relational methods before assigning it to products if I wanted to.
If I want to access all products that involve Germany I can do the following
Product.for_country | Product.from_country #=> Array[<Product...>...]
products = Product.for_country | Product.from_country #=> Array[<Product...>...]
Here I cannot chain more relational methods before assigning it to products since the result of the OR is an Array
not an ActiveRecord
::Relation.
My questions is how can I OR for_country with from_country and get a ActiveRecord::Relation
as a result?
Ideally something like the following Product.for_country(country).or(Product.from_country(country))
How can I make an 'OR' statement in ActiveRecord?
I know that isn't the exact answer to your question, but I'd say another method such as involving_country
which used this 'or' logic would make your other code much more readable than chaining from_country
and for_country
. Those methods, chained, don't really explain themselves very well.
精彩评论