繁体   English   中英

如何将SQL查询转换为优化的Rails Active Record查询?

[英]How to convert SQL query to optimized Rails Active Record query?

我有这个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")

但它没有用,我曾期望它能用。

有几件事情要解决和提出问题,使他们很难正确回答

  • 您如何在BankerOrganization之间建立关系?
  • 如之前所问:您期望什么?
  • 您是否为该软删除功能使用了一些gem( deleted_at is NULL )? (例如妄想症
  • 您可以提供从您的版本生成的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')

如果您对用户和组织使用上面提到的偏执狂宝石,则*.deleted_at is not null查询部分将被自动添加,这将ruby查询减少了。

User.select("concat(organizations.code, ' - ', users.name)")
    .includes(:organizations)
    .where('users.type = ?', 'Banker')
    .order('organizations.code ASC')

在极少数情况下,您对导轨不了解。 这是有关关联文章的链接。

可能对您的情况有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM