我有这个SQL查询,当我运行它时可以正常工作,但是我如何表示它并通过ActiveRecord获取相同的数据?
select concat(o.code, ' - ', u.name)
from users u join user_organizations uo on u.id = uo.user_id
join organizations o on uo.organization_id = o.id
where u.approved = true
and u.deleted_at is null
and o.deleted_at is null
and u.type = 'Banker'
order by o.code asc;
我试过这个
Banker.joins(:user_organizations => :organization)
.where(:approved => true)
.select("concat(organizations.code, users.name)")
.order("organizations.code asc")
但它没有用,我原以为它会奏效。
有一些事情需要解决和开放的问题,这些问题使得难以正确回答
- 你们在
Banker
和Organization
之间的关系是怎样的? - 如前所述:你期待什么?
- 您是否为此软删除功能(
deleted_at is NULL
(使用某些 GEM?(例如偏执狂( - 能否提供从您的版本生成的 SQL 查询?
我假设您的设置看起来像这样
class User < ApplicationRecord
has_and_belongs_to_many :organizations
end
class Organization < ApplicationRecord
has_and_belongs_to_many :users
end
如果是这样,您应该能够执行以下操作
User.select("concat(organizations.code, ' - ', users.name)")
.includes(:organizations)
.where('users.deleted_at is not null')
.where('organizations.deleted_at is not null')
.where('users.type = ?', 'Banker')
.order('organizations.code ASC')
如果您为用户和组织使用上面提到的偏执狂 gem,*.deleted_at is not null
查询部分将自动添加,从而将 ruby 查询减少到这样的 sth。
User.select("concat(organizations.code, ' - ', users.name)")
.includes(:organizations)
.where('users.type = ?', 'Banker')
.order('organizations.code ASC')
在极少数情况下,您不知道导轨。这是有关关联的文章的链接。
Scuttle可能对您的情况有用。