2011-10-10 39 views
1

简单的问题。目前,Post模型,这是我的设置为默认范围如何使用default_scope忽略基于布尔字段的条目

default_scope :order => 'posts.created_at ASC' 

我怎么能增加这只有那些:draft => false

另外,我怎样才能使一个非默认范围返回那些:draft => true

谢谢!

回答

3

在这种情况下不要使用default_scope。使用这些常规作用域:

scope :drafts, where(:draft => true) 
scope :published, where(:draft => false) 

如果你真的想使用default_scope(我不推荐,因为它限制了你,使你以后要解决它),你可以做这样的:

再次

@drafts = Post.unscoped.where(:draft => true) 

但是,如果你正在使用default_scope这意味着你想让它总是使用这些条件,并通过:

default_scope order('posts.created_at').where(:draft => false) 

,并在以后得到草稿你基本上告诉ActiveRecord不要做你明确告诉它的事情。对我来说,这是一个破解。

+0

+1 ..避免使用'default_scope',除非你知道你真的需要它。 – Zabba

+0

准时挨打,无论如何我想补充一句,“draft:true'也可以写作'scoped_by_draft true'。祝一切顺利! – ecoologic

+0

感谢您的提示,伙计们! – jay

相关问题