How to use unscoped on associated relations in Rai

2019-01-21 08:30发布

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

In other cases, I can use unscoped in order to bypass the default_scope, e.g. in Product.unscoped.find_by_title('abc'). However:

How to remove the scope when using associations of a record?

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.

7条回答
SAY GOODBYE
2楼-- · 2019-01-21 09:34

New answer

This question should help you figure out how to bypass the default where clause for your association.

It's worth repeating though that if you're regularly having to avoid a scope then it probably should be a default. Create a visible non-default scope and use that explicitly in your associations.

查看更多
登录 后发表回答