How to know if a model has 0 relations. Rails

0

I have a question about how to optimize a query, I'm doing it with a select to an active record query. How could I do this in a single SQL query.

Here, for example, is a request. maintenance_service_requests has a Has and belong to many with billing_documents, where billing_documents has a sender_id. What I do is get the maintenance requests that your billing_document does not have yet with a specific sender_id.

So now it works for me, but I know there is some way to do it with activeRecord only.

    
asked by Alexei Mamani 12.04.2018 в 02:35
source

1 answer

0

When you have a join(:some_model) , you can add a where in this way: join(:some_model).where(some_model: { attr1: ..., attr2: ... }) to filter according to attributes of the table with which you are doing the join.

So in your case, this would be as follows:

msrs_no_have_billings = maintenance_service_requests.includes(:billing_documents).where(billing_documents: { sender_id: billing_identifier.id })

This way you have left in 1 query.

    
answered by 12.04.2018 в 19:48