Reputation: 905
I have the following query that loads associations:
contacts = current_user.contacts.includes(:contact_lists).where(id: subscribed_contact_ids)
[DEBUG] Contact Load (2.6ms) SELECT "contacts".* FROM "contacts" WHERE "contacts"."user_id" = 7 AND "contacts"."id" IN (4273, 4275, 4277, 4278, 4281, 4285, 4297, 4305, 4307, 4308, 4315, 4318, 4323, 4326, 4331, 4333, 4344, 4349, 4359, 4361, 4368, 4372, 4373, 4378, 4382, 4389, 4392, 4394, 4404, 4428, 4450, 4469, 4473, 4489, 4490, 4495, 4497, 4498, 4501, 4505, 4514, 4520, 4525, 4536, 4545, 4554, 4555, 4561, 4568, 4572)
[DEBUG] Subscription Load (0.8ms) SELECT "subscriptions".* FROM "subscriptions" WHERE "subscriptions"."contact_id" IN (4273, 4275, 4277, 4278, 4281, 4285, 4297, 4305, 4307, 4308, 4315, 4318, 4323, 4326, 4331, 4333, 4344, 4349, 4359, 4361, 4368, 4372, 4373, 4378, 4382, 4389, 4392, 4394, 4404, 4428, 4450, 4469, 4473, 4489, 4490, 4495, 4497, 4498, 4501, 4505, 4514, 4520, 4525, 4536, 4545, 4554, 4555, 4561, 4568, 4572)
[DEBUG] ContactList Load (0.5ms) SELECT "contact_lists".* FROM "contact_lists" WHERE "contact_lists"."id" IN (9, 8)
I also need to get distinct contact_lists, basically i need to load the result of last query separately.
So the question is: is there way to load these contact lists without running the complex queries again?
The option to iterate through each record to get the contact_lists and then to remove duplicates is not attractive at all. The other option is to run complex join query again (seems not really good either):
contact_list_ids = current_user.subscriptions.select('distinct contact_list_id').where(contact_id: contact_ids).pluck(:contact_list_id)
current_user.contact_lists.where(id: contact_list_ids)
Those queries are cached somewhere. Is there way to access the query cache directly?
Upvotes: 0
Views: 59
Reputation: 3012
Here is a solution for your problem. But it requires you to monkey patch rails which might not be a great idea.
How do I get the last SQL query performed by ActiveRecord in Ruby on Rails?
I would rather iterate over the contacts and store the contact_lists
in a hash with their id as key. Then you do not need to worry about duplicates
contact_lists = {}
contacts.each { |c| c.contact_lists.each { |cl| contact_lists[cl.id] = cl } }
or something.
Upvotes: 1