我知道你可以在Rails中创建命名范围,它允许你指定可以在以后构建的条件:
named_scope :active,:conditions => {:active => true} ... MyModel.active.find(...)
这通过创建一个代理对象来工作,该代理对象直到稍后才进行评估.我想知道的是,是否可以创建一个动态的未命名范围?
我的意思是,有一种方法’foo’我可以去
scope = MyModel.foo(:conditions => {:target_id => 4})
然后传递范围作为代理对象,我可以做更多.finds或其他范围的调用?
解决方法
是的,请检查
Anonymous Scopes:
def find_products scope = Product.scoped({}) scope = scope.conditions "products.name LIKE ?","%#{keywords}%" unless keywords.blank? scope = scope.conditions "products.price >= ?",minimum_price unless minimum_price.blank? scope = scope.conditions "products.price <= ?",maximum_price unless maximum_price.blank? scope = scope.conditions "products.category_id = ?",category_id unless category_id.blank? scope end