简体   繁体   中英

In Ruby on Rails, how do I query for items that have no associated elements in a has_many :through relationship

I have a Contact model, and a User model, and a join table and each is HABTM more or less.

How can I query for the Contacts that have no users assigned to them? Driving me nuts.

Thanks

IMHO you should do a raw SQL query something along the lines of....

select c.*
from   contacts c left join contacts_users cu on c.id = cu.contact_id
where  cu.contact_id is null

I don't know of any pretty ORM-specific way to do it. Obviously you'll want to tailor the query to use the actual fields from your table.

I believe this thread is looking for the same thing right?

Want to find records with no associated records in Rails 3

If I understand you correctly, then I think it could be something like:

Contact.includes(:jointablenames).where( :jointablenames => {:contact_id => nil } )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM