Rails 3:如何根据控制器的方法创建命名范围?
在我的 ApplicationController
中,我有 demo_mode?
方法(当当前登录的用户类型为“demo”时,该方法返回 true
)。
Post
模型具有 publisher_id
字段,该字段引用 Users
表。
User
具有 user_type
字段,其可能值之一是“demo”。
底线:帖子 p
由“演示”用户发布,当且仅当:
User.find(p.publisher_id).user_type == "demo"
我想创建一个命名范围 Post.relevant
,它将返回:
- 所有帖子由“演示”用户发布,如果
demo_mode? == true
- 由非“演示”用户发布的所有帖子,如果
demo_mode? == false
您将如何创建这样一个命名范围?我应该将 demo_mode? 移动到其他地方吗?
In my ApplicationController
I have the demo_mode?
method (which returns true
when the currently logged in user type is "demo").
Post
model has the publisher_id
field, which refers to Users
table.
User
has the user_type
field, one of the possible values of which is "demo".
Bottom line: post p
was published by a "demo" user if and only if:
User.find(p.publisher_id).user_type == "demo"
I would like to create a named scope Post.relevant
that will return:
- all posts that were published by "demo" users, if
demo_mode? == true
- all posts that were published by non "demo" users, if
demo_mode? == false
How would you create such a named scope ? Should I move demo_mode?
to other place ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 lambda 创建动态作用域,并将会话信息保留在模型之外:
在模型中:
然后在控制器中:
Use a lambda to make a dynamic scope, and keep the session info out of the model:
In your model:
And then in the controller:
尝试这样的事情
Try something like this
如果我理解正确的话,演示状态是由会话决定的,因此只有控制器知道它。另一方面,控制器(或者可能是视图)是您想要查询范围的唯一位置。如果所有这些都是正确的,我将向 ApplicationController 添加一个方法,如下所示:
从技术上讲,这不是命名范围。然而,Rails 3 在命名范围和标准查询接口之间没有太大区别。
If I understand correctly, the demo state is determined by the session so only the controller knows about it. On the other hand, the controller (or possibly the view) is the only place where you would want to query the scope. If all of this is correct, I would add a method to ApplicationController like this:
Technically, this is not a named scope. Rails 3, however does not make much of a difference between named scopes and the standard query interface.