AnA*_*ice 6 ruby-on-rails ruby-on-rails-3
我在使用范围在rails中正常工作时遇到了一些麻烦.
我的模特:
class User < ActiveRecord::Base
default_scope :conditions => 'users.deleted_at IS NULL'
class Feed < ActiveRecord::Base
belongs_to :user, :foreign_key => :author_id
Run Code Online (Sandbox Code Playgroud)
当我打电话给以下人时:
feeds = Feed.includes(:user)
Run Code Online (Sandbox Code Playgroud)
我想为用户跳过default_scope.所以我试过了:
feeds = Feed.unscoped.includes(:user)
Run Code Online (Sandbox Code Playgroud)
但这并不是要从用户那里删除范围.有关如何使其工作的任何建议?谢谢
MrT*_*rus 16
您可以通过完成此.unscoped块形式,记录在这里:
User.unscoped do
@feeds = Feed.includes(:user).all
end
Run Code Online (Sandbox Code Playgroud)
请注意,默认范围是否适用取决于在实际执行查询时您是否在块内.这就是上面使用的原因.all,迫使查询执行.
因此,虽然上述工作,但不会 - 查询在.unscoped块外执行,默认范围将适用:
User.unscoped do
@feeds = Feed.includes(:user)
end
@feeds #included Users will have default scope
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4213 次 |
| 最近记录: |