[英]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")
但它沒有用,我曾期望它能用。
有幾件事情要解決和提出問題,使他們很難正確回答
Banker
和Organization
之間建立關系? deleted_at is NULL
)? (例如妄想症 ) 我認為您的設置看起來像這樣
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.