【问题标题】:Rails scope where account has user帐户拥有用户的 Rails 范围
【发布时间】:2017-11-08 19:01:25
【问题描述】:
我有一个帐户和一个用户模型,其中一个帐户有一个用户。所以在我的用户表中,我有 account_id。
我想为我的帐户创建一个范围,我可以在其中传递 has_user = TUE/FALSE 并返回有/没有用户的帐户。
scope :has_user, -> (has_user) { where(...) }
谁能帮忙写这个作用域?
【问题讨论】:
标签:
ruby-on-rails
ruby-on-rails-4
ruby-on-rails-5
【解决方案1】:
使用原始 sql,您可以使用 JOINS 编写更高效的查询,但这应该可以:
scope :has_user, -> (has_user) {
account_ids = User.where.not(account_id: nil).pluck(:account_id)
has_user ? where(id: account_ids) ? where.not(id: account_ids)
}
如果 Account has_one User 我假设那个 User belongs_to Account 并且你在你的 users 表上有一个 account_id。
【解决方案2】:
另一种方法是,
class Account < ApplicationRecord
has_one :user
scope :has_user, ->(has_user = true) {
criteria = (has_user == true ? 'IN' : 'NOT IN')
where("id #{criteria} (SELECT DISTINCT(account_id) FROM users)")
}
end
为 has_user 变量分配默认值 true
Account.has_user # Accounts with user
Account.has_user(false) # Accounts without user