轨道3默认的范围,范围与覆盖 [英] Rails 3 default scope, scope with override

查看:209
本文介绍了轨道3默认的范围,范围与覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,现有的应用程序的行为正在发生变化,它引起了我一个大难题。

我的应用程序有照片。照片都有一个状态:批处理,排队或完全。所有现有的照片应用程序是完整的。

99%的时间我只需要表现出完整的照片,并在所有的现有codeBase的,我需要每次调用照片将仅限于完整的照片。

然而,在涉及到上传和分类照片的画面,我需要能够很容易覆盖默认范围显示成批或排队的照片。

和许多人一样,我需要找到一种方法来轻松地覆盖在某些情况下默认的范围。我看了一下这些问题( 1 ,的 2 ),他们似乎并没有回答我要找的。

在code祝的工作是这样的:

 类照片<的ActiveRecord :: Base的
  ...
  default_scope其​​中(:状态=>'完成')
  适用范围:批量,unscoped.where(:状态=>批)
  适用范围:队列,unscoped.where(:状态=>排队)
  ...
结束
 

然而,这是行不通的。我试着在包装lambda表达式的范围方法,而且也不能工作。

我知道default_scope自带行李,但如果我不能覆盖那么我期待在加入范围内使用它:完整的... 并具有梳通过我现有的应用程序,以滤除未处理的照片在每次调用的照片,并添加 .complete

你将如何解决这个问题?

解决方案

 高清self.batch
  Photo.unscoped.where(:状态=>批)
结束

这个线程是更权威:重写一个Rails default_scope

I have a situation where the behavior of an existing app is changing and it's causing me a major headache.

My app has Photos. Photos have a status: "batch", "queue", or "complete". All the existing Photos in the app are "complete".

99% of the time I need to only show complete photos, and in all of the existing codebase I need every call to Photos to be limited to only complete photos.

However, in the screens related to uploading and classifying photos I need to be able to fairly easily override that default scope to show batched or queued photos.

Like many others, I need to find a way to easily override the default scope in certain situations. I looked at these questions (1, 2) and they don't seem to answer what I'm looking for.

The code I wish worked is this:

class Photo < ActiveRecord::Base
  ...
  default_scope where(:status=>'complete')
  scope :batch, unscoped.where(:status=>'batch')
  scope :queue, unscoped.where(:status=>'queue')
  ...
end

However, that doesn't work. I tried wrapping the scope methods in lambdas, and that didn't work either.

I realize default_scope comes with baggage, but if I can't use it with overrides then I'm looking at adding scope :complete ... and having to comb through every call to photos in my existing app and add .complete in order to filter unprocessed photos.

How would you solve this problem?

解决方案

def self.batch
  Photo.unscoped.where(:status=>"batch")
end

This thread is more authoritative: Overriding a Rails default_scope

这篇关于轨道3默认的范围,范围与覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆