开发者

How do I ignore entries based on boolean fields using default_scope

开发者 https://www.devze.com 2023-04-12 15:17 出处:网络
Simple question. Currently, for Post model, this is my setup for the default scope default_scope :order => \'posts.created_at ASC\'

Simple question. Currently, for Post model, this is my setup for the default scope

default_scope :order => 'posts.created_at ASC'

How can I augment this to only have those where :dra开发者_JAVA百科ft => false

Also, how can I make a non-default scope to return those where :draft => true?

Thanks!


Don't use default_scope in this case. Use these regular scopes:

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

If you really want to use default_scope (which I don't recommend as it limits you and makes you have to get around it later), you can do it like this:

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

and to get drafts later:

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

But again, if you're using default_scope it means that you want it to ALWAYS use those conditions, and by using unscoped you're basically telling ActiveRecord NOT to do something that you explicitly told it to. To me, this is a hack.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号