There a couple of things to address and open questions which make it difficult to answer properly
- How are your relations set up between
Banker and Organization?
- as asked before: what are you expecting?
- do you use some gem for this soft-delete feature (
deleted_at is NULL)? (e.g. paranoia)
- can you provide the generated SQL query from your version?
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.
concat(organizations.code, users.name)