1. you can use unless instead of if not
2. i think you can use txonomy.hostgroup_ids instead of pluck(:id) (should save one join imho)