Rails 3:如何根据 Controller 的方法创建命名范围? [英] Rails 3: How to create a named scope based on Controller's method?
问题描述
在我的 ApplicationController
中,我有 demo_mode?
方法(当当前登录的用户类型为demo"时返回 true
).
In my ApplicationController
I have the demo_mode?
method (which returns true
when the currently logged in user type is "demo").
Post
模型有 publisher_id
字段,它指的是 Users
表.
Post
model has the publisher_id
field, which refers to Users
table.
User
具有 user_type
字段,其可能的值之一是demo".
User
has the user_type
field, one of the possible values of which is "demo".
底线:帖子 p
是由演示"用户发布的,当且仅当:
Bottom line: post p
was published by a "demo" user if and only if:
User.find(p.publisher_id).user_type == "demo"
我想创建一个命名范围 Post.relevant
它将返回:
I would like to create a named scope Post.relevant
that will return:
- 演示"用户发布的所有帖子,如果
demo_mode?== 真
- 非演示"用户发布的所有帖子,如果
demo_mode?== 假
您将如何创建这样的命名范围?我应该将 demo_mode?
移到其他地方吗?
How would you create such a named scope ? Should I move demo_mode?
to other place ?
推荐答案
使用 lambda 来创建动态范围,并将会话信息保留在模型之外:
Use a lambda to make a dynamic scope, and keep the session info out of the model:
在您的模型中:
class Post < ActiveRecord::Base
scope :relevant, lambda {|demo_mode|
joins(:publisher).
where("publishers.user_type #{demo_mode ? '' : 'NOT'} LIKE 'demo'")
}
end
然后在控制器中:
posts = Post.relevant(demo_mode?)
这篇关于Rails 3:如何根据 Controller 的方法创建命名范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!