如何在Rails 3中取消关联记录

我在使用范围在rails中正常工作时遇到了一些麻烦。

我的模特:

class User  'users.deleted_at IS NULL' class Feed  :author_id 

当我打电话给以下人时:

 feeds = Feed.includes(:user) 

我想为用户跳过default_scope。 所以我试过了:

 feeds = Feed.unscoped.includes(:user) 

但这并不是要从用户那里删除范围。 有关如何使其工作的任何建议? 谢谢

您可以通过以块forms使用.unscoped来完成此操作,如下所示:

 User.unscoped do @feeds = Feed.includes(:user).all end 

请注意,默认范围是否适用取决于在实际执行查询时您是否在块内。 这就是为什么上面使用.all ,强制查询执行的原因。

因此,虽然上述工作,但不会 – 查询在.unscoped块之外执行,默认范围将适用:

 User.unscoped do @feeds = Feed.includes(:user) end @feeds #included Users will have default scope