2011-10-10 49 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