如何在 Rails3 中对关联关系使用 unscoped? [英] How to use unscoped on associated relations in Rails3?
问题描述
由于信息安全限制,我对产品有一个默认范围.
I have a default scope on products due to information security constraints.
class Product < ActiveRecord::Base
has_many :photos
default_scope where('visible = 1')
end
但是,在我关联的照片模型中,我还必须找到不应该显示的产品.
In my associated Photo model, however, I also have to find products that should not be visible.
class Photo < ActiveRecord::Base
belongs_to :product
end
my_photo.product
在其他情况下,我可以按顺序使用 unscoped绕过default_scope,例如在 Product.unscoped.find_by_title('abc')
中.但是:
In other cases, I can use unscoped in order to bypass the default_scope, e.g. in Product.unscoped.find_by_title('abc')
. However:
如何在使用记录关联时移除范围?
my_photo.unscoped.product
没有意义,因为 my_photo 没有名为 unscoped
的方法.my_photo.product.unscoped
也没有意义,因为 my_photo.product
可能已经为零.
my_photo.unscoped.product
does not make sense as my_photo does not have a method called unscoped
. Neither does my_photo.product.unscoped
make sense as my_photo.product
may already be nil.
推荐答案
哦.我骗了自己.认为以下方法行不通……但确实如此:
Oh. I fooled myself. Thought the following would not work... but it does:
Product.unscoped do
my_photo.product
end
请注意,您必须使用应该绕过的 default_scope
在模型上调用 unscoped.
Notice that you have to call unscoped on the model with the default_scope
that should be bypassed.
此外,必须尊重继承.如果您有 class InsuranceProduct
类 FinancialProduct
Product
中的 default_scope
,以下两种组合都可以使用:
Also, inheritance has to be respected. If you have class InsuranceProduct < Product
and class FinancialProduct < Product
and a default_scope
in Product
, all of the following two combinations will work:
InsuranceProduct.unscoped do
my_record.insurance_products
end
FinancialProduct.unscoped do
my_record.financial_products
end
Product.unscoped do
my_record.products
end
但是,尽管范围是在 Product
中定义的,但以下 将不起作用:
However, the following will not work although the scope is defined in Product
:
Product.unscoped do
my_record.financial_products
end
我想这是 Ruby/Rails 中 STI 的另一个怪癖.
I guess that's another quirk of STI in Ruby / Rails.
这篇关于如何在 Rails3 中对关联关系使用 unscoped?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!