0

鉴于我有以下代码

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

如果我想将产品制造并分发到德国,我可以执行以下操作

Product.for_country.from_country #=> ActiveRecord::Relation
products = Product.for_country.from_country #=> Array[<Product...>...]

在上述情况下,如果我愿意,我可以在将其分配给产品之前链接更多的关系方法。

如果我想访问所有涉及德国的产品,我可以执行以下操作

Product.for_country | Product.from_country #=> Array[<Product...>...]
products = Product.for_country | Product.from_country #=> Array[<Product...>...]

在这里,我无法在将更多关系方法分配给产品之前将其链接起来,因为 OR 的结果Array不是ActiveRecord::Relation。

我的问题是我如何 OR for_country 与 from_country 并得到ActiveRecord::Relation一个结果?

理想情况下,如下所示Product.for_country(country).or(Product.from_country(country))

4

1 回答 1

0

如何在 ActiveRecord 中进行“或”语句?

我知道这不是您问题的确切答案,但我想说另一种方法,例如involving_country使用这种“或”逻辑的方法会使您的其他代码比链接from_countryfor_country. 这些方法,链式的,并不能很好地解释自己。

于 2010-12-15T21:27:26.190 回答