开发者

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

开发者 https://www.devze.com 2023-02-09 15:11 出处:网络
I have a Contact model, and a User model, and a join table and each 开发者_运维问答is HABTM more or less.

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 } )
0

精彩评论

暂无评论...
验证码 换一张
取 消