如下两个model
class Product < ActiveRecord::Base
has_many :photos
default_scope where('visible = 1')
end
class Photo < ActiveRecord::Base
belongs_to :product
end
my_photo.product
输出为nil, 因为default_scope
使用unscope解决方式:
belongs_to :product, -> { unscope(where: :visible) }
另一个选择是覆盖getter方法和unscope super:
class Photo < ActiveRecord::Base
belongs_to :product
def product
Product.unscoped{ super }
end
end