gpt4 book ai didi

ruby-on-rails - Rails 4 ActiveRecord 包括(:model) without its default_scope

转载 作者:行者123 更新时间:2023-12-03 16:04:26 24 4
gpt4 key购买 nike

我的 Rails 应用程序中有以下情况。有两种模型,假设用户和公司:

class User < ActiveRecord::Base
belongs_to :company
default_scope -> {where(removed_at: nil)}
end


class Company < ActiveRecord::Base
has_many :users
end

我现在想要的是加载公司记录并包含用户
Company.unscoped.all.includes(:users)

什么将导致对包含默认范围的用户表的查询。
所以我得到了所有未删除的用户预取的公司记录。但在这种情况下,我也希望 remove_at 不为空的用户(=> 删除的用户记录)。 “无作用域”方法仅适用于 Company 模型,不适用于 User 模型。

有没有办法做到这一点?感谢您的任何想法!

最佳答案

这是我在 Rails 4.0 应用程序中使用的解决方案

class User < ActiveRecord::Base
belongs_to :company
default_scope -> {where(removed_at: nil)}
end

class UserUnscoped < User
self.default_scopes = []
end

class Company < ActiveRecord::Base
has_many :users, class_name: "UserUnscoped"
end

Company.unscoped.all.includes(:users)

关于ruby-on-rails - Rails 4 ActiveRecord 包括(:model) without its default_scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19291181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com