在 Ruby on Rails 中显示模型的所有可用命名范围

发布于 2024-08-31 19:27:14 字数 50 浏览 9 评论 0原文

特别是当您使用 Searchlogic 时。我很难猜测使用什么命名范围来实现我的需要。

Especially when you are using Searchlogic. It is kinda hard for me to guess what named scope to use to achieve what I need.

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

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

发布评论

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

评论(1

花想c 2024-09-07 19:27:14

您可以获取模型的所有定义的命名范围,使用

Model.scopes
=> {:one_scope_name=>#<Proc:0x0000...>, :other_scope_name=>#<Proc:0x0000...>, ... }

它为您提供一个散列,因此如果您只想要名称,请使用 Model.scopes.keys

但这只会为您提供已经定义的范围。它不会帮助您搜索逻辑生成的范围,因为,正如您可以在 文档< /a> (在引擎盖下),像 field_eq 等作用域仅在首次使用时创建:

Searchlogic 使用 method_missing
创建所有这些命名范围。
当它遇到 method_missing 时,它会创建
命名范围以确保它永远不会
缺少该名称的 hit 方法
再次范围。有点像缓存
机制。它的工作原理相同
时尚如 ActiveRecord 的“find_by_*
方法。这样只有命名的
创建您需要的范围并
仅此而已。

You can get all defined named scopes for a model, using

Model.scopes
=> {:one_scope_name=>#<Proc:0x0000...>, :other_scope_name=>#<Proc:0x0000...>, ... }

It gives you a hash, so if you want only names, use Model.scopes.keys

But this will give you only scopes, that are already defined. It won't help you will scopes, generated by searchlogic, because, as you can read in documentation (Under the hood section), scopes like field_eq etc are created only when they are first used:

Searchlogic utilizes method_missing
to create all of these named scopes.
When it hits method_missing it creates
a named scope to ensure it will never
hit method missing for that named
scope again. Sort of a caching
mechanism. It works in the same
fashion as ActiveRecord's "find_by_*"
methods. This way only the named
scopes you need are created and
nothing more.

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