加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在Rails 3中取消关联记录

发布时间:2020-12-16 21:21:36 所属栏目:百科 来源:网络整理
导读:我在使用范围在rails中正常工作时遇到了一些麻烦. 我的模特: class User ActiveRecord::Base default_scope :conditions = 'users.deleted_at IS NULL'class Feed ActiveRecord::Base belongs_to :user,:foreign_key = :author_id 当我打电话给以下人时: f
我在使用范围在rails中正常工作时遇到了一些麻烦.

我的模特:

class User < ActiveRecord::Base
  default_scope :conditions => 'users.deleted_at IS NULL'


class Feed < ActiveRecord::Base
  belongs_to :user,:foreign_key => :author_id

当我打电话给以下人时:

feeds = Feed.includes(:user)

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

feeds = Feed.unscoped.includes(:user)

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

解决方法

您可以使用.unscoped以块形式完成此操作,如文档 here所示:
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读