We have a table called Client and client belongs to a user in two ways, a client can have an updater and has a creator. It also belongs to a company.
belongs_to :creator, class_name: 'User'
belongs_to :updater, class_name: 'User'
I am trying to grab all clients for the current parent object company they belong to and then order them alphabetically by the name of their creator
Here is what I currently have tried
current_company.clients.includes(:creator).order("creator.name #{sort_dir}")
If I put :user in the includes it throws an error that user is not on the table.
Association named 'user' was not found on Client;
This was the closest I was able to get with what I found online.
CodePudding user response:
The easiest way to see how the query looks like is to call .to_sql.
You will see that when the join is performed it uses the table name, users, instead of the relation name, creator.
This should work:
current_company.clients.includes(:creator).order("users.name #{sort_dir}")
