RUBY ON RAILS查询关联关系

问题描述 投票:0回答:1
class Persson
   has_many : accounts
   has_many : computers, through : :accounts
end

class Account
   belongs_to : person
   belongs_to : computer
   scope :administrtor, -> { where(role : 'administrator') }
end

class Computer
  has_many :accounts
  has_many :person, though: :accounts
end

1.查找此人(身份证号码:39)是管理员的所有计算机。

2.找到所有在多台计算机上管理员的人。

3.找到只有一个管理员的所有计算机。

ruby-on-rails associations
1个回答
1
投票

嘿,请检查关联rails文档doc假设您正在使用PostgreSQL解决您的问题

1.

Person.includes(:accounts).find(1).computers.where("accounts.role =?", 'administrator')

2.

Person.where(id: Account.administrtor.group("accounts.person_id").having("count(accounts.person_id) > 1").pluck("accounts.person_id"))

3.

Computer.where(id: Account.administrtor.group("accounts.computer_id").having("count(accounts.computer_id) = 1").pluck("accounts.computer_id"))
© www.soinside.com 2019 - 2024. All rights reserved.