Can I create an *un*named scope in Rails?

蹲街弑〆低调 提交于 2019-12-10 15:39:45

问题


I know you can create named scopes in Rails, which allow you to specify conditions which can then be built on later:

named_scope :active, :conditions => {:active => true}

...

MyModel.active.find(...)

This works by creating a proxy object which isn't evaluated until later on. What I want to know is if it's possible to create a dynamic unnamed scope?

By which I mean, is there a method 'foo' with which I can go

scope = MyModel.foo(:conditions => {:target_id => 4})

and then pass scope around as a proxy object that I can do more .finds or other scoped calls on?


回答1:


Yes, check 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


来源:https://stackoverflow.com/questions/1914836/can-i-create-an-unnamed-scope-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!