我可以在 Rails 中创建*未*命名的范围吗?

发布于 2024-08-14 11:51:29 字数 428 浏览 8 评论 0原文

我知道您可以在 Rails 中创建命名范围,它允许您指定稍后可以构建的条件:

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

...

MyModel.active.find(...)

这通过创建一个代理对象来实现,该代理对象直到稍后才进行评估。我想知道是否可以创建动态命名范围?

我的意思是,是否有一个方法“foo”,我可以使用它

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

,然后将 scope 作为代理对象传递,我可以执行更多 .find 或其他操作作用域调用?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

茶花眉 2024-08-21 11:51:29

是的,请检查匿名范围

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文