I have this SQL query that works properly when I run it but how do I represent it and get the same data via 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;
I tried this
Banker.joins(:user_organizations => :organization)
.where(:approved => true)
.select("concat(organizations.code, users.name)")
.order("organizations.code asc")
but it didn't work and I had expected it to work.
There a couple of things to address and open questions which make it difficult to answer properly
Banker
and Organization
? deleted_at is NULL
)? (eg paranoia ) I assume that your setup looks sth like this
class User < ApplicationRecord
has_and_belongs_to_many :organizations
end
class Organization < ApplicationRecord
has_and_belongs_to_many :users
end
If so you should be able to do the following
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')
In case you are using the paranoia gem mentioned above for users and organizations the *.deleted_at is not null
query parts will be added automatically which reduces the ruby query to sth like this.
User.select("concat(organizations.code, ' - ', users.name)")
.includes(:organizations)
.where('users.type = ?', 'Banker')
.order('organizations.code ASC')
For the rare case you don't know about the rails guides. Here's the link to the article about associations .
盾可能对您的情况有用。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.