如何获得在轨道3所有数据库行的范围有多大? [英] How to get a scope for all database rows in rails 3?
问题描述
假设我们以下设置:
class Post < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :posts
end
进一步假设用户有一个布尔属性管理员,这表明,如果他是一个全球性的管理或没有。
assume further the user has a boolean attribute 'admin', which indicates if he is a global admin or not.
我想写一个为用户类,称为visible_posts的方法(或范围有多大?)。如果用户是没有管理,它应该只返回自己的岗位。如果他是admin的方法应该返回所有文章在系统中。
I want to write a method (or a scope?) for the User class, called 'visible_posts'. If the user is no admin, it should return just its own posts. If he IS admin the method should return all posts in the system.
我的第一次尝试是这样的:
My first attempt was something like this:
class User < ActiveRecord::Base
[...]
def visible_posts
if admin?
Post.all
else
posts
end
end
end
这里的问题是,Post.all返回一个数组,但我宁愿希望有一个ActiveRecord ::关系就像我的帖子后获得与它的工作。
Problem here is that Post.all returns an Array, but I would rather like to have an ActiveRecord::Relation like I get from posts to work with it later on.
是它在某种程度上可能得到一个ActiveRecord ::关系的重新presents的所有帖子?
Is it somehow possible to get an ActiveRecord::Relation that represents ALL posts ?
推荐答案
您可以做 Post.scoped
我想用Rails
You can do Post.scoped
i guess in Rails
和后面这一点,你可以调用。所有
来获取结果
And later on this you can call .all
to fetch the results
这篇关于如何获得在轨道3所有数据库行的范围有多大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!